Featured

    Featured Posts

String in Python Part-2



String Methods In Python

Changing the capitalization of a string

§  Python's string type provides many functions that act on the capitalization of a string.

str.upper()

§  str.upper takes every character in a string and converts it to its uppercase equivalent, for example:

word=input('enter string in lowercase')
print('Original String is:- ',word)
print('capitalization of a string is:- ',word.upper())
Output:
enter string in lowercase python
Original String is: - python
capitalization of a string is: - PYTHON

str.lower()

§  str.lower does the opposite; it takes every character in a string and converts it to its lowercase equivalent:

word=input('enter string in UpperCase')
print('Original String is:- ',word)
print('capitalization of a string is:- ',word.lower())
Output:
enter string in UpperCase   PYTHON
Original String is:-  PYTHON
capitalization of a string is:-  python

str.capitalize()

§  str.capitalize returns a capitalized version of the string, that is, it makes the first character have upper case and the rest lower:

word=input('enter string ')
print('Original String is:- ',word)
print('capitalization of a string is:- ',word.capitalize())
Output:
enter string python
Original String is:-  python
capitalization of a string is:-  Python

str.title()

§  str.title returns the title cased version of the string, that is, every letter in the beginning of a word is made upper case and all others are made lower case:

word=input('enter string ')
print('Original String is:- ',word)
print('Titlelization of a string is:- ',word.title())
Output
enter string india is my country
Original String is:-  india is my country
Titlelization of a string is:-  India Is My Country


str.swapcase()

§  str.swapcase returns a new string object in which all lower case characters are swapped to upper case and all upper case characters to lower:


word=input('enter string ')
print('Original String is:- ',word)
print('swapcase of a string is:- ',word.swapcase())
Output
enter string  india Is my cOUNtry
Original String is:-  india Is my cOUNtry
swapcase of a string is:-  INDIA iS MY CounTRY


Removing spaces from the string:

|- Stripping unwanted leading/trailing characters from a string


str.strip([chars])

§  str.strip acts on a given string and removes (strips) any leading or trailing characters contained in the argument chars; if chars is not supplied or is None, all white space characters are removed by default. For example:

word=input('enter string ')
print('Original String is:- ',word)
print('After Removel leading and trailing space of a string is:-',word.strip())
Output
enter string     python is a prog lang   
Original String is:-      python is a prog lang   
After Removel leading and trailing space of a string is: - python is a prog lang



§  If chars is supplied, all characters contained in it are removed from the string, which is returned. For example:

word=input('enter string ')
print('Original String is:- ',word)
print('After Removel leading and trailing space of a string is:-',word.strip('$'))
Output
enter string $python is a prog lang
Original String is:-  $python is a prog lang
After Removel leading and trailing space of a string is:- python is a prog lang



str.rstrip([chars]) and str.lstrip([chars])

§  rstrip()===>To remove spaces at right hand side

§  lstrip()===>To remove spaces at left hand side 3

word=input('enter string ')
print('Original String is:- ',word)
print('After Removel leading space of a string is:-',word.rstrip())
print('After Removel trailing space of a string is:-',word.lstrip())
Output
enter string    python is a prog lang   
Original String is:-     python is a prog lang   
After Removel leading space of a string is:-    python is a prog lang
After Removel trailing space of a string is:- python is a prog lang   

Counting number of times a substring appears in a string

§  One method is available for counting the number of occurrences of a sub-string in another string, str.count.

str.count(substring)

str.count(substring,begin,end)

|- from begin index to end-1 index substring


s='python is a prog lang and java is prog lang'
print(s.count('o'))     # The OutPut will be 3
print(s.count('lang'))  # The OutPut will be 2
print(s.count('java'))  # The OutPut will be 1
print(s.count('lang',20,len(s))) # The OutPut will be 1


Replace all occurrences of one substring with another substring

§  Python's str type also has a method for replacing occurrences of one sub-string with another sub-string in a given string.

§  S.replace(oldstring,newstring)

s='python is prog lang'
print(s)    # The Output will be python is prog lang

s=s.replace('python','java')
print(s)  # The output will be java is prog lang


Write a python program to count the total number of occurrences of a given character in a string without using any loop?

word=input('enter string ')
char=input('enter letter for which')
count =len(word)-len(word.replace(char,''))
print('Number of occurances of',char ,' in ',word,' = ',count)

Output
enter string  python again python again
enter letter for which a
Number of occurrences of a  in  python again python again  =  4



Split a string based on a delimiter into a list of strings

str.split(sep=None, maxsplit=-1)

§  We can split the given string according to specified seperator by using split() method.

§  str.split takes a string and returns a list of substrings of the original string

l=s.split(seperator)

§  The default seperator is space. The return type of split() method is List



word=input('enter string ')
word_list=word.split()
print('Original String is:- ',word)
print('Lis of Word:-',word_list)

Output

enter string india is my country
Original String is: - india is my country
Lis of Word: - ['india', 'is', 'my', 'country']


print( "            ".split())#The Output will be []
list='java,python,angular,php,sql'.split(',')
print(list)



§  The default is to split on every occurrence of the delimiter, however the maxsplit parameter limits the number of splitting’s that occur. The default value of -1 means no limit:

str='python is a prog lang'
print(str.split('a',maxsplit=0))
print(str.split('a',maxsplit=1))
print(str.split('a',maxsplit=2))
print(str.split('a',maxsplit=-1))

Output
['python is a prog lang']
['python is ', ' prog lang']
['python is ', ' prog l', 'ng']
['python is ', ' prog l', 'ng']


Write a python program to count the number of words in a string?

word=input('enter string ')
word_list=word.split()
count=0
for w in word_list:
    print(w)
    count+=1
print('Total Word:-',count)

enter string india is my country


Output
india
is
my
country

Total Word:- 4




Finding Substrings is present in Given String:

§ there are 4 method available in python to finding position of substring in given string.

1.     find()
2.     rfind()
3.     index()
4.     rindex()

1. find() Method In Python:

s.find(substring)

§  This method returns the index position of first occurrence of the given substring. If the given substring is not available then it will return -1. 


s='java and python is very very easy a prog lang'
print(s.find('java'))#The Output will be 0
print(s.find('python'))#The Output will be 9
print(s.find('very'))#The Output will be 19

Note: -

§  By default, find () method can search total string. but if you want to search with-in the boundaries then you have to require to specify the boundaries to search.

s.find(substring,bEgin,end)

§  It will always search from begin index to end-1 index

s='java and python is very very easy a prog lang'
print(s.find('java'))#The Output will be 0
print(s.find('python',10,20))#The Output will be -1
print(s.find('very',24,30))#The Output will be 24


2. rfind() Method In Python:

s.rfind(substring)

§  This method returns the index position of last matching of the given substring. If the given substring is not available then it will return -1.

s='java and python is very very easy a prog lang'
print(s.rfind('java'))#The Output will be 0
print(s.rfind('python'))#The Output will be 9
print(s.rfind('very'))#The Output will be 24
print(s.rfind('php'))#The Output will be -1

3. index() Method In Python:

s.index(substring)

§  This method returns the index position of first occurrence of the given substring. If the given substring is not available then we will get ValueError.

s='java and python is very very easy a prog lang'
print(s.index('java'))#The Output will be 0
print(s.index('python'))#The Output will be 9
print(s.index('very'))#The Output will be 19
print(s.index('php'))

ValueError: substring not found

2. rindex() Method In Python:

s.rfind(substring)

§  This method returns the index position of last matching of the given substring. If the given substring is not available then it will return -1.

s='java and python is very very easy a prog lang'
print(s.rindex('java'))#The Output will be 0
print(s.rindex('python'))#The Output will be 9
print(s.rindex('very'))#The Output will be 24
print(s.rindex('php'))

#The Output will be ValueError: substring not found

Write a python program to find the following output

email=input('enter email')
userName=''
server=''
domain=''
atpos=email.find('@')
dotpos=email.rfind('.')
if atpos!=-1 and dotpos!=-1:
    userName=email[0:atpos]
    server=email[atpos+1:dotpos]
    domain=email[dotpos+1:]
print('userName :=',userName)
print('Server :=',server)
print('Domain :=',domain)


www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews