Basics of Python – String Methods

In this Page, We are Providing Basics of Python – String Methods. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – String Methods

String methods

Below are listed some of the string methods which support both strings and Unicode objects. Alternatively, some of these string operations can also be accomplished using functions of the string module.

str.isalnum( )
Return True, if all characters in the string are alphanumeric, otherwise False is returned.

>>> str=" this2009 ”
>>> str.isalnum ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalnum( )
False

str. isalpha ( )
Return True, if all characters in the string are alphabetic, otherwise False is returned.

>>> str=" this "
>>> str.isalpha ( )
True
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.isalpha ( )
False

str.isdigit( )
Return True, if all characters in the string are digits, otherwise False is returned.

>>> str="this2009" 
>>> str.isdigit ( )
False
>>> str=" 2009 "
>>> str.isdigit ( )
True

str . isspace ( )
Return True, if there are only whitespace characters in the string, otherwise False is returned.

>>> str= "    "
>>> str.isspace ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.isspace ( )
False

str.islower ( )
Return True, if all cased characters in the string are in lowercase and there is at least one cased character, false otherwise.

>>> str=" THIS is string example. . . .wow! ! ! "
>>> str.islower( )
False
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.islower ( )
True
>>> str=" this2009 "
>>> str.islower ( )
True
>>> str=" 2009 "
>>> str.islower ( )
False

str.lower ( )
Return a string with all the cased characters converted to lowercase.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.lower ( )
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. lower (s), where s is a string.

>>> import string 
>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! " 
>>> string:lower(str)
' this is String example. . . .wow ! ! ! '

str.isupper ( )
Return True, if all cased characters in the string are uppercase and there is at least one cased character, otherwise False is returned.

>>> str="THIS IS STRING EXAMPLE. . . .WOW ! ! ! "
>>> str.isupper ( )
True
>>> str=" THIS is string example. . . .wow ! ! ! "
>>> str.isupper ( )
False

str.upper ( )
Return a string with all the cased characters converted to uppercase. Note that str . upper () . isupper () might be False, if string contains uncased characters.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.upper ( )
' THIS IS STRING EXAMPLE. . . . WOW ! ! ! '
>>> str.upper ( ) .isupper ( )
True
>>> str="@1234@"
>>> str.upper ( )
' @1234@ '
>>> str.upper ( ).isupper ( )
False

The above can be imitated using the string module’s function string. upper (s), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string.upper (str)
' THIS IS STRING EXAMPLE. . . .WOW ! ! ! ’
>>> string.upper (str).isupper ( )
True 
>>> str="@1234@"
>>> string.upper(str)
'@1234@' 
>>> string.upper (str).isupper ( )
False

str.capitalize ( )
Return a string with its first character capitalized and the rest lowercase.

>>> str=" this Is stRing example. . . . wow ! ! ! "
>>> str.capitalize ( )
' This is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, capitalize (word), where the word is a string.

>>> str=" this Is stRing example. . . .wow ! ! ! "
>>> string.capitalize ( str )
' This is string example. . . .wow ! ! ! '

str.istitle ( )
Return True, if the string is title cased, otherwise False is returned.

>>> str=" This Is String Example. . .Wow ! ! ! "
>>> str . istitle ( )
True
>>> str=" This is string example. . . .wow ! ! ! "
>>> str.istitle ( )
False

str.title ( )
Return a title cased version of the string, where words start with an uppercase character and the remaining characters are lowercase. It will return unexpected results in cases where words have apostrophes etc.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.title ( )
' This Is String Example. . . .wow ! ! ! '
>>> str=" this isn't a float example. . . .wow ! ! ! "
>>> str.title ( )
" This Isn'T A Float Example. . . .Wow ! ! ! "

str.swapcase ( )
Return a copy of the string with reversed character case.

>>> str='' This is string example. . . .WOW ! ! ! "
>>> str . swapcase ( ) 
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. swap case (s), where s is a string.

>>> str=" This is string example. . . .WOW ! ! ! "
>>> string, swapcase (str) 
' tHIS IS STRING EXAMPLE. . . .wow ! ! ! '

str.count(sub[,start[, end]])
Return the number of non-overlapping occurrences of sub-string sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> str.count (sub , 4 , 40)
2
>>> sub=" wow "
>>> str.count(sub)
1

The above can be imitated using string module’s function string. count (s, sub [, start [, end] ] ), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> sub=" i "
>>> string.count( str , sub , 4 ,40 )
2
>>> sub=" wow "
>>> string.count( str,sub )
1

str.find(sub[,start[,end]])
Return the lowest index in the string where the sub-string sub is found, such that sub is contained in the slice s [ start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1, if the sub is not found.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>>> str1.find ( str2 )
15
>>> str1.find ( str2 , 10 )
15 
>>> str1.find ( str2 , 40 )
-1

The above can be imitated using the string module’s function string. find (s, sub [, start [, end] ]), where s is a string.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam " 
>>> string.find ( str1 , str2 )
15 
>>> string.find(str1 , str2 , 10 )
15
>>> string.find( str1 , str2 , 40)
-1

The find ( ) method should be used only if there is a requirement to know the position of the sub. To check if the sub is a sub-string or not, use the in operator:

>>> ' Py ' in ' Python '
True

str.rfind(sub[,start[, end]] )
Return the highest index in the string where the sub-string sub is found, such that sub is contained within s [start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

>>> str1=" this is really a string example. . . .wow ! ! ! "
>>> str2=" is "
>>> strl.rfind ( str2 )
5
>>> str1.rfind ( str2 , 0 , 10 )
5
>>> strl.rfind ( str2 , 10 , 20 )
-1

The above can be imitated using the string module’s function string.rfind(s, sub [, start [, end] ] ), where s is a string.

>>> str1=" this is really a string example. . . .wow ! ! ! " 
>>> str2=" is "
>>> string.rfind ( str1 , str2 )
5
>>> string.rfind ( str1 , str2 , 0 , 10 )
5
>>> string.rfind ( str1 , str2 , 10 , 0 )
-1

str.index ( sub [ , start [ , end ] ] )
Like find ( ), but raise ValueError when the sub-string is not found.

>>> str1=" this is string example. . . .wow ! ! ! "
>>> str2=" exam "
>.> str1. index ( str2 ) 
15 
>>> str1.index ( str2 , 10 )
15 
>>> str1.index ( str2 , 40 )
Traceback ( most recent call last ) :
File "<pyshell#38>", line 1, in <module>
str1 . index ( str2 , 40 ) 
ValueError: substring not found

The above can’ be imitated using string module’s function string, index (s, sub [, start [, end] ] ), where s is a string.

>>> str1 = " this is string example. . . .wow ! ! ! " 
>>> str2=" exam "
>>> string.index ( str1 , str2 )
15
>>> string. index ( str1 , str2 ,10 )
15
>>> string, index ( str1 , str2 , 40 )
Traceback ( most recent call last ) :
File " <stdin> ", line 1, in <module>
File " C : \ Python27 \ lib \ string.py ", line 328, in index 
return s . index ( *args )
ValueError: substring not found

str.rindex ( sub [ , start [ , end ] ] )
Like rfind ( ), but raises ValueError when the sub-string sub is not found.

>>> str1="this is string example. . . .wow ! ! ! "
>>> str2=" is "
>>> strl.rindex ( str1 , str2 )
5
>>> str1.rindex ( str2 , 10 , 20 )
Traceback (most recent call last) : 
File " <stdin> ", line 1, in <module>
ValueError: substring not found

The above can be imitated using the string module’s function string. rfind ( s, sub [, start [, end] ] ), where s is a string.

>>> str1= " this is string example. . . .wow ! ! ! "
>>> str2=" is "
>>> string.rindex ( str1 , str2 )
5
>>> string.rindex ( str1 , str2 , 10 , 20)
Traceback (most recent call last) :
File "<stdin>", line 1, in <module>
File." C : \ Python27 \ lib \ string.py" , line 337, in rindex 
return s.rindex ( *args )
ValueError: substring not found

str.startswith (prefix [ , start [ , end ] ] )
Return True, if string starts with the prefix, otherwise return False. The prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With an optional end, stop comparing string at that position.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.startswith( ' this ' )
True
>>> str.startswith( ' is ' , 2)
True
>>> str.startswith( ' this ' , 10 , 17 )
False
>>> pfx=( ' the ' , ' where ' , ' thi ' )
>>> str. startswith ( pfx )
True

str.endswith ( suffix [ , start [ , end ] ] )
Return True, if the string ends with the specified suffix, otherwise return False. The suffix can also be a tuple of suffixes to look for. The “est starts from the index mentioned by optional argument start. The comparison is stopped indicated by optional argument end.

>>> str=" this is string example. . . .wow ! ! ! "
>>> suffix=" wow ! ! ! "
>>> str.endswith ( suffix )
True
>>> suffix= ( " tot ! ! ! ", " wow ! ! ! " )
>>> str.endswith ( suffix )
True
>>> str.endswith ( suffix,20 )
True
>>> suffix= " is "
>>> str.endswith( suffix , 2 , 4 )
True
>>> str.endswith( suffix , 2 , 6 )
False
>>> str.endswith ( (' hey ’,' bye ',' w ! ! ! ' ) )
True

str. join ( iterable )
Return a string which is the concatenation of the strings in the iterable. The separator between elements is the string str providing this method.

>>> str="-" 
>>> seq= ( " a " , " b " , " c " )
>>> str. join ( seq )
' a-b-c '
>>> seq=[ " a " , " b " , " c " ]
>>> str.join (seq) 
' a-b-c '

The above can be imitated using the string module’s function string, join (words [, sep] ), where words is a list or tuple of strings, while the default value for sep is a single space character.

>>> str="-"
>>> seq= ( "a", "b", "c")
>>> string. join (seq, str)
'a-b-c'
>>> seq= [ ”a”, "b”, "c" ]
>>> string.join(seq,str) 
' a-b-c ’

str.replace ( old , new [ , count ] )
Return a string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

>>> str=" this is string example. . . . wow ! ! ! this is really string"
>>> str.replace (" is "," was ")
'thwas was string example. . . .wow ! ! ! thwas was really string’
>>> str=" this is string example. . . .wow ! ! ! this is really string "
>>> str.replace (" is "," was ", 3)
'thwas was string example. . . .wow ! ! ! thwas is really string '

The above can be imitated using the string module’s function string. replace (s, old, new [, max replace ] ), where s is a string and may replace is the same as count (discussed above).

>>> str=" this is string example. . . .wow ! ! ! this is really string"
>>> string.replace (str, " is "," was " )
'thwas was string example. . . .wow ! ! ! thwas was really string'
>>> str=" this is string example. . . .wow ! ! ! this is really string"
>>> string.replace (str," is "," was ", 3)
'thwas was string example. . . .wow ! ! ! thwas is really string'

str.center ( width [ , fillchar ] )
Return centered string of length width. Padding is done using optional argument fillchar (default is a space).

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.center ( 40 ,' a ' )
' aaaathis is string example. . . .wow ! ! ! aaaa'
>>> str="this is string example. . . .wow ! ! ! "
>>> str.center (40)
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, center (s, width [, fillchar ] ), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string.center(str, 40 ,’ a ' )
'aaaathis is string example. . . .wow ! ! ! aaaa'
>>> str="this is string example .... wow!!!"
>>> string.center(str,40)
' this is string example. . . .wow ! ! ! '

str.1just ( width [ , fillchar ] )
Return the string left-justified in a string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if the width is less than or equal to len(str).

>>> str="this is string example. . . .wow! ! ! " 
>>> str . 1 just (50, ' 0 ' )
'this is string example. . . .wow ! ! !000000000000000000 '
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.1just (50)
' this is string example. . . .wow ! ! ! '
>>> str="this is string example. . . .wow ! ! ! "
>>> str.1just (10)
' this is string example. . . .wow ! ! ! '

The above can be imitated using string module’s function string. 1 just (s, width [,fill char] ), where s is a string.

>>> str="this is string example. . . .wow ! ! ! "
>>> string.1just ( str , 50, ' 0 ' )
' this is string example. . . .wow ! ! ! 000000000000000000 '
>>> str=" this is string example. . . .wow ! ! ! "
>>> string.1just ( str , 50 )
'this is string example. . . .wow ! ! ! '

str.rjust ( width [ ,fillchar ] )
Return the right-justified string of length width. Padding is done using the optional argument fillchar (default is a space). The original string is returned if the width is less than or equal to len(str).

>>> str="this is string example. . . .wow ! ! ! "
>>> str.rjust ( 50 , ' 0 ' )
'000000000000000000this is string example. . . .wow ! ! ! '
>>> str=" this is string example. . . .wow ! ! ! "
>>> str.rjust ( 10 , ' 0 ' )
' this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. rjust (s, width [, fillchar] ), where s is a string.

>>> str="this is string example. . . .wow ! ! ! "
>>> string .r just (str, 50, ’ 0 ’ )
' 000000000000000000this is string example. . . .wow ! ! ! '
>>> str="this is string example. . . .wow ! ! ! "
>>> string.rjust (str , 10 , ' 0 ' ) .
' this is string example. . . .wow ! ! ! '

str.zfill ( width )
Return a string of length width, having leading zeros. The original string is returned, if the width is less than or equal to len(str).

>>> str=” this is string example. . . .wow ! ! ! "
>>> str.zfill (40)
'00000000this is string example. . . .wow ! ! ! ' 
>>> str . zf ill ( 45)
' 0000000000000this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string, zfill (s, width), where s is a string.

>>> str=" this is string example. . . .wow ! ! ! "
>>> string . zfill ( str , 40 ) 
'00000000this is string example. . . .wow ! ! ! ’
>>> string . zfill ( str , 45 ) 
' 0000000000000this is string example. . . .wow ! ! ! '

str.strip ( [ chars ] )
Return a string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" 0000000this is string example. . . . wow ! ! ! 0000000 "
>>> str.strip ( ' 0 ' )
'this is string example. . . .wow ! ! ! '

The above can be imitated using the string module’s function string. strip (s [, chars ] ), where s is a string.

>>> str=" 0000000this is string example. . . .wow ! ! ! 0000000"
>>> string, strip (str, ’ 0 ’ )
'this is string example. . . .wow ! ! ! '

str.1strip ( [ chars ] )
Return a string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.1strip ( ) 
'this is string example. . . .wow ! ! ! '
>>> str="88888888this is string example. . . .wow ! ! ! 8888888 "
>>> str.1strip ( ' 8 ' ) 
'this is string example. . . .wow ! ! ! 8888888 '

The above can be imitated using string module’s function string. lstrip (s [, chars] ), where s is a string.

>>> str="     this is string example. . . .wow ! ! !       "
>>> string.1strip (str)
' this is string example. . . .wow ! ! ! '
>>> str=" 888S8888this is string example. . . .wow ! ! ! 8888888 "
>>> string.1strip ( str , ' 8 ' )
' this is string example. . . .wow ! ! ! 8888888 '

str.rstrip ( [ chars ] )
Return a string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace.

>>> str=" this is string example. . . .wow ! ! ! "
>>> str.rstrip ( )
' this is string example. . . .wow ! ! ! '
>>> str="88888888this is string example. . . .wow ! ! ! 8888888 "
>>> str.rstrip (' 8 ')
' 88888888this is string example. . . .wow ! ! ! '

The above can be imitated using string module’s function string.rstrip (s [, chars] ), where s is a string.

>>> str="   this is string example. . . .wow ! ! ! "
>>> string.rstrip ( str )
' this is string example. . . .wow ! ! ! '
>>> str=  "88888888this is string example. . . .wow ! ! ! 8888888 "
>>> string.rstrip ( str,' 8 ' )
' 88888888this is string example. . . .wow ! ! ! '

str.partition(sep)
Split the string at the first occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str="       this is string example. . . .wow ! ! !        "
>>> str.partition (' s ')
('        thi ' ,  ' s ' , ' is string example. . . .wow ! ! !       ' )

str.rpartition (sep)
Split the string at the last occurrence of sep, and return a tuple containing the part before the separator, the separator itself, and the part after the separator.

>>> str="         this is string example. . . .wow! ! !       "
>>> str.rpartition (' s ' )
(' this is ', ' s ', ' tring example. . . .wow ! ! ! ' )

str.split ( [ sep [ , maxsplit ] ] )
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1 elements). If maxsplit is not specified or -1, then all possible splits are made. If sep is not specified or None, any whitespace string is a separator.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> str . split ( )
['Line1-abcdef', ' Line2-abc ', ' Line4-abcd ' ]
>>> str.split(' ',1)
[' Line1-abcdef ', '\nLine2-abc \nLine4-abcd ' ]

The above can be imitated using string module’s function string, split (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="Line1-abcdef \nLine2-abc \nLine4-abcd"
>>> string.split (str)
[ ' Line1-abcdef ', ' Line2-abc ', ' Line4-abcd ' ]
>>> string. split ( str,'   ',1 )
[ ' Line1-abcdef ', ' \nLine2-abc \nLine4-abcd ' ]

str.rsplit ( [ sep [ , maxsplit ] ] )
Return a list of the words from the string using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit () behaves like split () which is described in detail below.

>>> str="       this is string example. . . .wow ! ! !       "
>>> str.rsplit ( )
['this', 'is', 'string', 'example. . . .wow ! ! ! ' ]
>>> str.rsplit ( ' s ' )
['       thi ', ' i ', '   ', ' tring example. . . .wow ! ! ! ' ]

The above can be imitated using string module’s function string. rsplit (s [, sep [, maxsplit ] ] ), where s is a string.

>>> str="          this is string example. . . . wow ! ! !        "
>>> string. rsplit ( str )
[ ' this ' ,  ' is ' , ' string ' , ' example. . . .wow ! ! ! ' ]
>>> string. rsplit ( str , ' s ' )
['          thi' ; ' i ', ' ', 'tring example. . . .wow ! ! !                 ' ]

str. splitlines ( [ keepends ] )
Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keeping is given.

>>> str="1ine1-a b c d e f\n1ine2- a b c\ n\n1ine4- a b c d "
>>> str.splitlines ( )
[ ' Line1-a b c d e f',   ' Line2- a b c ' , '   ' , ' Line4- a b c d ' ]
>>> str. splitlines (0)
[ ' Line1-a b c d e f ', ' Line2- a b c ', '    ', ' Line4- a b c d ' ]
>>> str.splitLines ( Fa1se )
[ ' Line1-a b c d e f ' , ' Line2- a b c ', '    ', ' Line4- a b c d ' ]
>>> str.sp1itLines (1)
[ ' Line1-a b c d e f\n ' , ' Line2- a b c\n', '\n', ' Line4- a b c d ' ]
>>> str.splitLines ( True )
[ ' Line1-a b c d e’ f\n', ' Line2- a b c\n', ' Line4- a b c d ' ]

str.translate ( table [ , deletechars ] )
Return a string having all characters occurring in the optional argument delete chars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256.

The maketrans ( ) function (discussed later in this section) from the string module is used to create a translation table. For string objects, set the table argument to None for translations that only delete characters.

>>> str=' this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans ( ' e ' , ' E ' )
>>> str.translate ( tab )
' this is string ExamplE. . . .wow ! ! ! '
>>> str.translate ( tab , ' ir ' )
' ths s stng ExamplE. . . .wow ! ! ! '
>>> str.translate ( None , ' ir ' )
' ths s stng example. . . .wow ! ! ! '

The above can be imitated using string module’s function string. translate (s, table [, deletechars ] ), where s is a string.

>>> str=’ this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans (' e ',' E ')
>>> string.translate ( str , tab )
' this is string ExamplE. . . .wow ! ! ! '
>>> string.translate ( str , tab ,' ir ' )
' ths s stng ExamplE. . . .wow ! ! ! '
>>> string.translate ( str , None ,' ir ' )
' ths s stng example. . . .wow ! ! ! '

The following functions are there in the string module but are not available as string methods.

string.capwords(s[,sep])
Split the argument s into words using str. split (), then capitalize each word using str. capitalize ( ), and join the capitalized words using str. join ( ). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space, and leading and trailing whitespace is removed, otherwise, sep is used to split and join the words.

>>> str=" this is string example. . . .wow ! ! ! ''
>>> string.capwords (str)
' This Is String Example. . . .Wow ! ! ! '
>>> string.capwords (str, '    ' )
' This Is String Example. . . .Wow ! ! !    '
>>> string, capwords ( str,' s ' )
' this is sTring example. . . . wow ! ! ! ' 

string.maketrans ( from , to )
Return a translation table suitable for passing to translate (), that will map each character in from into the character at the same position in to, from and to must have the same length.

>>> str=' this is string example. . . .wow ! ! ! '
>>> tab=string.maketrans ( ' t! ' , ' T. ' )
>>> string.translate ( str , tab )
'This is sTring example. . . .wow. . . '
>>> string.translate ( str , tab ,' ir ' )
' Ths s sTng example. . . .wow. . . '
>>> string.translate ( str , None , ' ir ' )
' ths s stng example. . . .wow ! ! ! '

Python String Programs