Python String Methods explained with examples

Python String Methods.

Python has useful string methods which you can use to operate on the strings.




capitalize()
Return a copy of the string with only its first character capitalized. For 8-bit strings, this method is locale-dependent. 
text = 'hello world'
text = text.capitalize()
print(text)
_______________________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Hello world
 
 
 
casefold()
Converts string into lower case. 
text = 'Hello World'
text = text.casefold()
print(text)
_______________________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
hello world
 
 
center( width[, fillchar])
Return centered in a string of length width. Padding is done using the specified fillchar (default is a space). Changed in version 2.4: Support for the fillchar argument. 
text = 'Hello World'
text1 = text.center(20)
print(text1)
text2 = text.center(20,'*')
print(text2)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Hello World
****Hello World*****
 
 
count( sub[, start[, end]])
Return the number of occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation. 
text = 'Hello World. Hello humans'
c = text.count('Hello')
print(c)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
2
 
 
decode( [encoding[, errors]])
Decodes the string using the codec registered for encoding. encoding defaults to the default string encoding. errors may be given to set a different error handling scheme. The default is 'strict', meaning that encoding errors raise UnicodeError. Other possible values are 'ignore', 'replace' and any other name registered via codecs.register_error, see section 4.8.1. New in version 2.2. Changed in version 2.3: Support for other error handling schemes added. 
text = "Less than zero"
encoded = text.encode('utf-8')
print(encoded)

decoded = encoded.decode('utf-8')
print(decoded)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
2b'Less than zero'
Less than zero

 
 
encode( [encoding[,errors]])
Return an encoded version of the string. Default encoding is the current default string encoding. errors may be given to set a different error handling scheme. The default for errors is 'strict', meaning that encoding errors raise a UnicodeError. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error, see section 4.8.1. For a list of possible encodings, see section 4.8.3. New in version 2.0. Changed in version 2.3: Support for 'xmlcharrefreplace' and 'backslashreplace' and other error handling schemes added. 
text = 'I live in Roßkamper Straße'
x = text.encode()
print(x)
__________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

b'I live in Ro\xc3\x9fkamper Stra\xc3\x9fe'
 
 
endswith( suffix[, start[, end]])
Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position. Changed in version 2.5: Accept tuples as suffix. 
text = 'Check if the string ends with dot.'
x = text.endswith('.')
print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
 
expandtabs( [tabsize])
Return a copy of the string where all tab characters are expanded using spaces. If tabsize is not given, a tab size of 8 characters is assumed. 
txt = "H\te\tl\tl\to Human"

x = txt.expandtabs(2)

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

H e l l o Human

 
 
find( sub[, start[, end]])
Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found. 
txt = "They say: finder keeper"
x = txt.find('finder')
print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

10
 
 
index( sub[, start[, end]])
Like find(), but raise ValueError when the substring is not found. 
text = 'Hello World. Hello humans'
c = text.index('World')
print(c)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

6
 
 
isalnum( )
Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent.
txt = "Atari65XE"
x = txt.isalnum()

print(x)
__________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
 
isalpha( )
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. 
txt = "Atari"
x = txt.isalpha()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
True

 
 
isdigit( )
Return true if all characters in the string are digits and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. 
txt = "1979"
x = txt.isdigit()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
islower( )
Return true if all cased characters in the string are lowercase and there is at least one cased character, false otherwise. For 8-bit strings, this method is locale-dependent. 
txt = "small world"
x = txt.islower()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
 
isspace( )
Return true if there are only whitespace characters in the string and there is at least one character, false otherwise. For 8-bit strings, this method is locale-dependent. 
txt = "   "
x = txt.isspace()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
 
istitle( )
Return true if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return false otherwise. For 8-bit strings, this method is locale-dependent. 
txt = "Hello Humans"
x = txt.istitle()

print(x)

____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
 
isupper( )
Return true if all cased characters in the string are uppercase and there is at least one cased character, false otherwise. For 8-bit strings, this method is locale-dependent. 
txt = "HELLO WORLD"
x = txt.isupper()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com

True
 
join( seq)
Return a string which is the concatenation of the strings in the sequence seq. The separator between elements is the string providing this method. 
t = ("Cow ", "Chicken", "Horse")
x = ",".join(t)

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Cow ,Chicken,Horse
 
ljust( width[, fillchar])
Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). Changed in version 2.4: Support for the fillchar argument. 
txt = "Python"
x = txt.ljust(20)

print(x, "is Awesome")
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Python is Awesome
 
 
lower( )
Return a copy of the string converted to lowercase. For 8-bit strings, this method is locale-dependent. 
txt = "Hello PEOPLE"
x = txt.lower()

print(x)
________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
hello people
 
 
lstrip( [chars])
Return a copy of the 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. The chars argument is not a prefix; rather, all combinations of its values are stripped: >>> ' spacious '.lstrip() 'spacious ' >>> 'www.example.com'.lstrip('cmowz.') 'example.com' Changed in version 2.2.2: Support for the chars argument. 
txt = "**** Asterix ***** "
x = txt.lstrip('*')

print("No", x, "on the left")
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
No Asterix ***** on the left
 
 
partition( sep)
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
txt = "Programming with Python is fun."
x = txt.partition("Python")

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
('Programming with ', 'Python', ' is fun.')
 
 
replace( old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced. 
txt = "We are going to Mallorca"
x = txt.replace("Mallorca", "Bahamas")

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
We are going to Bahamas
 
 
rfind( sub [,start [,end]])
Return the highest index in the string where substring 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. 
txt = "I have a dog, mine dog is awesome"
x = txt.rfind('dog')

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
19
 
 
rindex( sub[, start[, end]])
Like rfind() but raises ValueError when the substring sub is not found. 
txt = "I have a dog, mine dog is awesome"
x = txt.rindex('dog')

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
19
 
 
rjust( width[, fillchar])
Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). Changed in version 2.4: Support for the fillchar argument. 
txt = "Python"
x = txt.rjust(11,'*')

print(x, "is five star.")
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
*****Python is five star.
 
 
rpartition( sep)
Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.
txt = "Keep learning, Python is awesome"
x = txt.rpartition("Python")

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
('Keep learning, ', 'Python', ' is awesome')
 
 
rsplit( [sep [,maxsplit]])
Return a list of the words in 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. 
txt = 'Cow, Chicken, Weasel'
x = txt.rsplit(", ")

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
['Cow', 'Chicken', 'Weasel']
 
 
rstrip( [chars])
Return a copy of the 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. The chars argument is not a suffix; rather, all combinations of its values are stripped: >>> ' spacious '.rstrip() ' spacious' >>> 'mississippi'.rstrip('ipz') 'miss.
txt = 'We all____'
x = txt.rstrip('_')

print(x, 'need a space.')
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
We all need a space.
 
 
split( [sep [,maxsplit]])
Return a list of the words in 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, then there is no limit on the number of splits (all possible splits are made).Splitting an empty string or a string consisting of just whitespace returns an empty list. 
txt = "Make a list of string"

x = txt.split()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
['Make', 'a', 'list', 'of', 'string']
 
 
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 keepends is given and true.  
txt = "This string had a line\nThis was second line"
x = txt.splitlines()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
['This string had a line', 'This was second line']
 
 
startswith( prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position. Changed in version 2.5: Accept tuples as prefix. 
txt = "Old MacDonald had a farm "
x = txt.startswith("Old")

print(x)____________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
True
 
 
strip( [chars])
Return a copy of the 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. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped: >>> ' spacious '.strip() 'spacious' >>> 'www.example.com'.strip('cmowz.') 'example' Changed in version 2.2.2: Support for the chars argument. 
txt = '***** Star *****'
x = txt.strip('*')
print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Star
 
 
swapcase( )
Return a copy of the string with uppercase characters converted to lowercase and vice versa. For 8-bit strings, this method is locale-dependent. 
txt = "Apples were for FREE today"
x = txt.swapcase()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
aPPLES WERE FOR free TODAY
 
 
title( )
Return a titlecased version of the string: words start with uppercase characters, all remaining cased characters are lowercase. For 8-bit strings, this method is locale-dependent. 
txt = "Evertyhing is going to be all right"
x = txt.title()

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Evertyhing Is Going To Be All Right
 
 
translate( table[, deletechars])
Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. You can use the maketrans() helper function in the string module to create a translation table. For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted. Note, a more flexible approach is to create a custom character mapping codec using the codecs module (see encodings.cp1251 for an example). 
replacement= {86:  74}
txt = 'Vet'

print(txt.translate(replacement))
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
Jet
 
 
upper( )
Return a copy of the string converted to uppercase. For 8-bit strings, this method is locale-dependent. 
text = 'Hello world. Hello humans'
c = text.upper()
print(c)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
HELLO WORLD. HELLO HUMANS
 
 
zfill( width)
Return the numeric string left filled with zeros in a string of length width. The original string is returned if width is less than len(s). 
txt = "Zero"
x = txt.zfill(10)

print(x)
____________________________________________________________________________
/usr/bin/python3.8 https://viteac.blogspot.com
000000Zero
 

You can donate me so I can afford to buy a coffee myself, this will help me to keep going and create more content that you find interesting.


Many thanks
Stay Happy and Keep Coding :-)
 


Comments