capitalize() : First char of the input string is converted to upper case
First char is changed to upper case. No parameter is taken by this method.
my_str="welcome to plus2net.com"
print(my_str.capitalize())
Welcome to plus2net.com
center() : Centers the string
my_str="plus2net.com"
print(my_str.center(30))
Output is here ( check the blank space at both sides of the text.
plus2net.com
casefolod(): Changing to Lower case chars
All chars are changed to lower case
my_str="Welcome to Plus2net Python"
print(my_str.casefold())
Output is here
welcome to plus2net python
count() : Counting the number of presence of a sting
Find out number of occurrence of string inside the main string.
my_str.count(search_string,start,end))
search_string
: String to be searched for matching inside main string.
start
: Optional , search can be started from this position
end
: Optional , search can be ended from this position.
my_str="Welcome to plus2net.com"
print(my_str.count('co')) # Output is 2
print(my_str.count('co',4)) # Output is 1
print(my_str.count('co',4,18)) # Output is 0
endswith() : Check if string ends with input string
Check if given string ends with input
search_string , returns
True if string ends with input
search_string otherwise
false
my_str.endswith(search_string,start,end))
search_string
: String to be checked at the end of the main string.
start
: Optional , check to start from this position
end
: Optional , check to end from this position.
my_str="Welcome to plus2net.com"
print(my_str.endswith('com')) # Output is True
print(my_str.endswith('com',4,6)) # Output is False
print(my_str.endswith('com',3,6)) # Output is True
print(my_str.endswith('net',16,19)) # Output is True
print(my_str.endswith('net')) # Output is False
expandtabs() : Update the length of Tab
By default expandtabs() ads 8 space by replacing all tab characters. We can set the number of spaces by giving input parameter.
my_str.expandtabs(number))
number
: optional , number of space to replace tab character.
my_str='a\tbc\tdef\tghij\tklmno'
my_str=my_str.expandtabs(1)
print(my_str)
The output is here
p l u s 2 n e t . c o m
Change the parameter to higher value and see the result.
my_str='a\tbc\tdef\tghij\tklmno'
my_str=my_str.expandtabs(3)
print(my_str)
Output
a bc def ghij klmno
find() : Search string and get matching position
Check if the search string is within our main string, if found then the position of matching string is returned. If not found then -1 is returned.
my_str.find(search_string,start,end))
search_string
: String to be checked inside the main string.
start
: Optional , search to start from this position
end
: Optional , serch to end from this position.
my_str="Welcome to plus2net.com"
print(my_str.find('co')) # Output is 3
print(my_str.find('co',4)) # Output is 20
print(my_str.find('co',4,18)) # Output is -1
We can use
index()
method also to find the position but
find()
method returns -1 if not found but
index()
method raise an exception if not found.
index(): Search string and get matching position
Check if the search string is within our main string, if found then the position of matching string is returned. If not found then this method raise an exception.
my_str.index(search_string,start,end))
search_string
: String to be checked inside the main string.
start
: Optional , search to start from this position
end
: Optional , serch to end from this position.
my_str="Welcome to plus2net.com"
print(my_str.index('co')) # Output is 3
print(my_str.index('co',4)) # Output is 20
print(my_str.index('co',4,18)) # ValueError: substring not found
The last line will generate exception.
We can use
find()
method also to search and find the position but
find()
method returns -1 if not found but
index()
method raise an exception if not found.
isalnum() : Check for alphanumeric chars
Checks for alphanumeric characters in a string. Returns
true if only number and alphabets are present and returns
False if any thing other than alphanumeric characters are present.
my_str='plus2net'
print(my_str.isalnum()) # Output is True
my_str='Welcome to plus2net'
print(my_str.isalnum()) # Output is False (presence of Space)
isalpha(): Check if all chars are alphabet or not
Returns True if all chars are alphabets in a string, Otherwise False is returned.
my_str='plus2net'
print(my_str.isalpha()) # Output is False
my_str='Welcome'
print(my_str.isalpha()) # Output is True
my_str='#1234'
print(my_str.isalpha()) # Output is False
my_str='12.34'
print(my_str.isalpha()) # Output is False
isdecimal(): check if all chars are decimal or not
Returns True if all chars are decimal ( 0 to 9) in a string, Otherwise False is returned.
my_str='12345'
print(my_str.isdecimal()) # Output is True
my_str='234ab'
print(my_str.isdecimal()) # Output is False
my_str='234.45'
print(my_str.isdecimal()) # Output is False
isdigit(): Check if all chars are digit or not
Returns True if all chars are digit in a string, Otherwise False is returned.
my_str='012345'
print(my_str.isdigit()) # Output is True
my_str='12#34'
print(my_str.isdigit()) # Output is False
my_str='abc1234'
print(my_str.isdigit()) # Output is False
my_str='\u0035' # Unicode of digit 5
print(my_str.isdigit()) # Output is True
isdigit(): Check if all chars are digit or not
Returns True if all chars are digit in a string, Otherwise False is returned.
my_str='012345'
print(my_str.isdigit()) # Output is True
my_str='12#34'
print(my_str.isdigit()) # Output is False
my_str='abc1234'
print(my_str.isdigit()) # Output is False
my_str='\u0035' # Unicode of digit 5
print(my_str.isdigit()) # Output is True
isidentifier() : Check if string is an identifier or not
Returns True if given string is an identifier, otherwise returns False.
What is an identifier?
identifiers can contain chars ( both lower and upper case ), numbers and underscore.
It can’t start with number
It can’t contain space or any other special chars within it.
my_str='_abc45'
print(my_str.isidentifier()) # Output is True
my_str='ab#cd'
print(my_str.isidentifier()) # Output is False ( # not allowed )
my_str='A_abc1234'
print(my_str.isidentifier()) # Output is True
my_str='pq?rs'
print(my_str.isidentifier()) # Output is False ( ? not allowed)
my_str='pq rs'
print(my_str.isidentifier()) # Output is False ( space not allowed)
my_str='12ab'
print(my_str.isidentifier()) # Output is False ( Can't start with number)
islower() : Check if all chars are in lower case or not
Returns True if all chars in a string are in lower case, otherwise rturns False
my_str='_abc45'
print(my_str.islower()) # Output is True
my_str='ab#cd'
print(my_str.islower()) # Output is True
my_str='A_abc1234'
print(my_str.islower()) # Output is False
my_str='pq?rs'
print(my_str.islower()) # Output is True
my_str='pq rs'
print(my_str.islower()) # Output is True
my_str='12ab'
print(my_str.islower()) # Output is True
isnumeric() : Check if all chars of input string are numeric or not
my_str='abc_45'
print(my_str.isnumeric()) # Output is False
my_str='1234#56'
print(my_str.isnumeric()) # Output is False
my_str='12.34'
print(my_str.isnumeric()) # Output is False
my_str='1234'
print(my_str.isnumeric()) # Output is True
isprintable() : Check if all chars are printable or not
Returns True if all chars are printable , otherwise False
my_str='Welcome to plus2net'
print(my_str.isprintable()) # Output is False
my_str='Welcome \t to plus2net'
print(my_str.isprintable()) # Output is False ( presence of Tab \t)
my_str='Welcome to plus2net \n'
print(my_str.isprintable()) # Output is False ( presence of line break \n)
my_str='1234'
print(my_str.isprintable()) # Output is True
isspace() : Check if all chars are white space or not
Returns True if all chars in a string are white space, otherwise False
my_str='Welcome to plus2net'
print(my_str.isspace()) # Output is False
my_str=' '
print(my_str.isspace()) # Output is True
my_str=' \n '
print(my_str.isspace()) # Output is True ( presence of line break \n)
my_str=' \t '
print(my_str.isspace()) # Output is True ( presence of tab \t )
istitle() : Check if all words starts with upper case letters
Returns True if all words starts with Upper Case and other chars are in lower case
my_str='Welcome To Python'
print(my_str.istitle()) # Output is True
my_str='Welcome to Python'
print(my_str.istitle()) # Output is False
my_str='WELCOME TO PYTHON'
print(my_str.istitle()) # Output is False ( All letters in Upper case )
my_str='Welcome to python'
print(my_str.istitle()) # False ( All words are not starting with upper case)
isupper() : Check if all chars are in Upper case or not
Returns True if all chars in a string are in Upper case, otherwise returns Fals
my_str='WELCOME TO PYTHON'
print(my_str.isupper()) # Output is True
my_str='Welcome to Python'
print(my_str.isupper()) # Output is False
join() : Joining elements to form string
String method join can join all elements by using one delimiter. We can apply join method to list, tuple, set and dictionary.
my_list=['Alex','Ronald','John']
output='*'.join(my_list)
print(output) # Alex*Ronald*John
my_tuple=('Alex','Ronald','John')
output='#'.join(my_tuple)
print(output) # Alex#Ronald#John
my_set={'Alex','Ronald','John'}
output=' '.join(my_set)
print(output) # Alex Ronald John
my_dict={'a':'Alex','b':'Ronald','c':'John'}
output='%'.join(my_dict)
print(output) # a%b%c ( only keys are present ( not values ))
ljust() : left justified string filler
Add left justified filler strings of specified width
my_string.ljust(width, filler)
width
: left justified string of width
filler
: optional, string can be used to fill the width
my_str='Welcome to'
output=my_str.ljust(15,'#')
print(output, 'plus2net')
Output is here
Welcome to##### plus2net
lower() : Change all chars to lowercase
my_str='Welcome to Plus2net'
output=my_str.lower()
print(output)
Output is here
welcome to plus2net
lstrip(): Removes space or chars from left side of the string
By default lstrip() will remove space from left of the string, we can also specify chars to be removed
my_str=' Plus2net'
output=my_str.lstrip()
print(output)
my_str='**plus2net'
output=my_str.lstrip('*')
print(output) # removes * from left
my_str='**## welcome plus2net'
output=my_str.lstrip('*# welcome')
print(output) # removes all left of plus2net
Output is here
Plus2net
plus2net
plus2net
partition() : Break a string into three parts using the input search string
partition() returns a three element tuple by breaking the string using input search string. Three parts here.
1. Left part of the matched string
2. The searched string
3. Right part of the matched string
my_str='Welcome to Plus2net'
output=my_str.partition('to')
print(output)
Output is here
('Welcome ', 'to', ' Plus2net')
We can add one more line to display the last element
print(output[2])
Output
plus2net
By using
partition()
method you can separate domain part and userid part of an email address.
replace() : Search and replace string inside a main string
Search for a string inside a main string and if found then replace it with another string
main_string.replace(search_string, replace_string, count)
search_string
: Required , string to search within main string
replace_string
: Required, string to replace if matching is found
count
: Number of times the replacement to happen. By default all matches will be replaced.
my_str='Welcome to PHP section of plus2net'
output=my_str.replace('PHP','Python')
print(output)
my_str='Welcome to PHP section of plus2net. PHP has many buit-in functions'
output=my_str.replace('PHP','Python')
print(output)
my_str='Welcome to PHP section of plus2net. PHP has many buit-in functions'
output=my_str.replace('PHP','Python',1)
print(output)
my_str='Welcome to PHP section of plus2net'
output=my_str.replace('MySQL','Python')
print(output) # Nothing replaced as no matching found
Output is here
Welcome to Python section of plus2net
Welcome to Python section of plus2net. Python has many buit-in functions
Welcome to Python section of plus2net. PHP has many buit-in functions
Welcome to PHP section of plus2net
rfind():Find the rightmost matching of search string and return the position
Returns the rightmost matching position of the search string in a main string
main_string.rfind(search_string, start, end)
search_string
: Required, String to be searched and position is returened if found.
start
: Optional, Starting position of search , by default it is from 0 or starting position of string
end
: Optional , ending position of search, by default it is end of the string.
my_str='Welcome to plus2net.com Python section'
output=my_str.rfind('co')
print(output) # output is 20
my_str='Welcome to plus2net.com Python section'
output=my_str.rfind('co',10,21)
print(output) # output is -1
my_str='Welcome to plus2net.com Python section'
output=my_str.rfind('co',10,22)
print(output) # output is 20
Output is here
20
-1
20
If the searched string is not found then -1 is returned by rfind() method, however rindex() method raise an exception if not found
rindex():Find the rightmost matching of search string and return the position
Returns the rightmost matching position of the search string in a main string
main_string.rindex(search_string, start, end)
search_string
: Required, String to be searched and position is returened if found.
start
: Optional, Starting position of search , by default it is from 0 or starting position of string
end
: Optional , ending position of search, by default it is end of the string.
my_str='Welcome to plus2net.com Python section'
output=my_str.rindex('co')
print(output) # output is 20
my_str='Welcome to plus2net.com Python section'
output=my_str.rindex('co',10,22)
print(output) # output is 20
my_str='Welcome to plus2net.com Python section'
output=my_str.rindex('co',10,21)
print(output) # output is -1
Output
20
20
Traceback (most recent call last):
File "D:/my_py/string-rindex.py", line 10, in
output=my_str.rindex('co',10,21)
ValueError: substring not found
rindex() method raise an exception if searched string is not found but
rfind() returns -1 if searched string is not found. That is the main difference between
rfind() and
rindex()
rjust(): Right align the string by using another string as filler
Returns right aligned string with filler char, by default space is used as filler.
my_str.rjust(length,filler)
length : length of the string required
filler : Optional, char can be used to fill the length after right justify. Blank space is used by default.
my_str='Welcome to'
output=my_str.rjust(15,' ')
print(output, 'plus2net')
Output
Welcome to plus2net
my_str='Welcome to'
output=my_str.rjust(15,'#')
print(output, 'plus2net')
output
#####Welcome to plus2net
rpartition() : Break a string into three parts using the input search string
partition() returns a three element
tuple by breaking the string using input search string. Three parts are here.
1. Left part of the matched string
2. The searched string
3. Right part of the matched string
my_str='Welcome to Plus2net'
output=my_str.rpartition('to')
print(output)
Output is here
('Welcome ', 'to', ' Plus2net')
We can add one more line to display the last element
print(output[2])
Output
plus2net
If matching string is not found then rpartition() returns the tuple with 3rd element as full string.
my_str='Welcome to Plus2net'
output=my_str.rpartition('ab')
print(output)
Output is here
('', '', 'Welcome to Plus2net')
If we use
partition() in place or
rpartition() the output is here ( the difference between
rpartition() and
partition() )
('Welcome to Plus2net', '', '')
rsplit(): split the string by using delimiter
rsplit() returns a list after breaking a string using delimiter and max value
my_str.rsplit(delimiter,max_value)
delimiter
: required, to be used to break the string
max_value
: optional , the number of elements in output plus one. Default value is -1 so it includes all occurance.
my_list="'Alex','Ronald','John'"
my_list=my_list.rsplit(',')
print(my_list)
my_list="'Alex','Ronald','John'"
my_list=my_list.rsplit(',',1)
print(my_list)
output
["'Alex'", "'Ronald'", "'John'"]
["'Alex','Ronald'", "'John'"]
rstrip(): Removes space or chars from right side of the string
By default rstrip() will remove space from right of the string, we can also specify chars to be removed
my_str='Plus2net '
output=my_str.rstrip()
print(output)
my_str='plus2net**'
output=my_str.rstrip('*')
print(output) # removes * from right
my_str='plus2net *#*#'
output=my_str.rstrip('*#')
print(output) # removes all right
Output is here
plus2net
plus2net
plus2net
split(): split the string by using delimiter
split() returns a list after breaking a string using delimiter and max value
my_str.split(delimiter,max_value)
delimiter
: required, to be used to break the string
max_value
: optional , the number of elements in output plus one. Default value is -1 so it includes all occurance.
my_list="'Alex','Ronald','John'"
my_list=my_list.split(',')
print(my_list)
my_list="'Alex','Ronald','John'"
my_list=my_list.split(',',1)
print(my_list)
output
["'Alex'", "'Ronald'", "'John'"]
["'Alex'", "'Ronald','John'"]
By using
rsplit() in place of
split(), the output will change like this. ( diference betweeen
rsplit() and
split() )
["'Alex'", "'Ronald'", "'John'"]
["'Alex','Ronald'", "'John'"]
splitlines(): split the string by using line breaks as delimiter
splitlines() returns a list after breaking a string using line breaks as delimiter
my_str.splitline(keeplinebreaks)
keeplinebreaks
: optional, True or False, by default it is False for not retaining line breaks
Output
my_str='Welcome\n to\n Plus2net'
output=my_str.splitlines()
print(output)
my_str='Welcome\n to\n Plus2net'
output=my_str.splitlines(True)
print(output)
Output is here
['Welcome', ' to', ' Plus2net']
['Welcome\n', ' to\n', ' Plus2net']
startswith():Check if the string starts with specified string or not
Returns True if the main string starts with specified search string, otherwise returns False
main_string.startswith(search_string, start, end)
search_string
: Required, String to be searched to check to match starting of the main string.
start
: Optional, Starting position of search , by default it is from 0 or starting position of string
end
: Optional , ending position of search, by default it is end of the string.
my_str='Welcome to plus2net.com Python section'
output=my_str.startswith('Wel')
print(output) # output is True
my_str='Welcome to plus2net.com Python section'
output=my_str.startswith('co',3)
print(output) # output is True
my_str='Welcome to plus2net.com Python section'
output=my_str.startswith('co',20,24)
print(output) # output is True
Output is here
True
True
True
strip(): Removes space or chars from left & right side of the string
By default
strip() will remove space from left(leading) and right(trailing) of the string, we can also specify chars to be removed
my_str=' Plus2net '
output=my_str.strip()
print(output)
my_str='*****plus2net**'
output=my_str.strip('*')
print(output) # removes * from both sides
my_str='*#*# plus2net *#*#'
output=my_str.strip('*# ')
print(output) # removes * ,# and space from both sides
Output is here
plus2net
plus2net
plus2net
swapcase(): Upper case chars to Lower case and and vice versa
All upper case chars are changed to lower case and lower case chars are changed to upper case
my_str='Welcome to plus2net Python Section'
output=my_str.swapcase()
print(output)
Output is here
wELCOME TO PLUS2NET pYTHON sECTION
title(): Change First letter of each word to upper case
my_str='welcome to plus2net python section'
output=my_str.title()
print(output)
my_str='welcome #id 15of plus2net'
output=my_str.title()
print(output)
Output
Welcome To Plus2Net Python Section
Welcome #Id 15Of Plus2Net
This also changes the first char after any number of special chars ( check plus2Net )
translate() , maketrans() : Search replace and delete of set of chars.
str_update=str_input.maketrans(str_search,str_replace,str_delete)
str_search
: Required, Chars to be searched
str_replace
: Required, Chars to be replaced ( mapped to searched chars )
str_delete
: Optional, Chars to be replaced with None ( deleted in final string )
Length of
str_search should be equal to length of
str_replace
the method
maketrans() returns a dictionary (
str_update ) with chars mapped for search and replace and this can be used for translate().
str_search='abc' # search chars
str_replace='xyz' # replace chars
str_delete='pqr' # delete chars
str_input='abcdefghpqr' #input string
str_update=str_input.maketrans(str_search,str_replace,str_delete)
print(str_update) # dictionary output with chars mapped.
print("input string : ",str_input)
print("Output string: ",str_input.translate(str_update))
Output
{97: 120, 98: 121, 99: 122, 112: None, 113: None, 114: None}
input string : abcdefghpqr
Output string: xyzdefgh
upper(): All chars changed to Upper case
All chars are changed to upper case letters , no parameter is taken by this mehod.
my_str='Welcome to plus2net Python section'
output=my_str.upper()
print(output)
Output
WELCOME TO PLUS2NET PYTHON SECTION
zfill(): Fill the string with zeros
Fill zeros upto the input length of the string
my_str='plus2net'
output=my_str.zfill(15)
print(output)
my_str='25'
output=my_str.zfill(5)
print(output)
output is here
0000000plus2net
00025