All string methods of Python explained.
Table of Contents
Introduction
Python supports 45 built-in string methods as of python version 3.8.2. All string methods return a new value and it does not change the original value. With string, methods are used for basic transformation and searching. So, we are going to discuss all 45 built-in string methods with an example.
Methods are the function that is attached to an object or a variable.
Syntax to use methods with object or variable
Whenever we are using methods to an object or variable; the method name should be attached to an object name with a dot followed by an open and close bracket. For instance;
>>>username = “Karma Dorji”
>>>print(username.upper())
KARMA DORJI
In the above example, the username is a variable and it holds string data type “Karma Dorji”. The upper() is a method attached to a variable name to convert the string to an upper case letter. We will discuss more later.
Displaying all 45 built-in methods of string
How to check the total number of methods we can use with string in python?
We have to use the dir() function and pass str as an argument. The command is >>>dir(str).
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__',
'__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__',
'__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit',
'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind',
'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> n = ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>> len(n)
45
Python interpreter has an offline guide to help us on how to use a method. It briefly explains the particular method with syntax. For that, we have to use the help() function and it takes the method name as an argument attached to the data type. For example, if you want to know about the upper() method we have used in the previous example; the command should be >>>help(str.upper)
>>> help(str.upper)
Help on method_descriptor:
upper(self, /)
Return a copy of the string converted to uppercase.
45 string methods with an example
1. capitalize()
Converts first character upper case and rest lower case.
Example:
>>>lang = "python"
>>>print(lang.capitalize())
Python
2. casefold()
Return a version of the string suitable for caseless comparisons.
Example:
>>> lang = "pyThon"
>>> print(lang.casefold())
python
3. center()
Returns a centered string of length width. This method takes two parameters, the first is the width and the second is an optional fill char. The fill char is a character that is used to fill the left and right padding of the string (default is a space).
Example:
>>> address = "Bhutan"
# Without fillchar, default space is added before and after
>>> print(address.center(10))
Bhutan
# With fillchar, "#" is added before and after to make width of the string 10
>>> print(address.center(10, '#'))
##Bhutan##
4. count()
Returns the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.
Example:
>>> fruit = "Banana"
>>> print(fruit.count("a"))
3
>>> print(fruit.count("a", 2,6))
2
5. encode()
Encode the string using the codec registered for encoding. If no encoding is specified, UTF-8 will be used.
Example:
>>> name = "åle"
>>> print(name.encode())
b'\xc3\xa5le'
6. endswith()
Returns True if the string ends with the specified suffix, False otherwise.
Example:
>>> address = "Bhutan"
>>> print(address.endswith("n"))
True
>>> print(address.endswith("h"))
False
7. expandtabs()
Returns a copy where all tab characters are expanded using spaces. If tab size is not given, a tab size of 8 characters is assumed.
Example:
>>>greet = "H\te\tl\tl\to"
>>>print(f"Without expandtabs method: {greet}")
Without expandtabs method: H e l l o
>>>print(f"With expandtabs method: {greet.expandtabs(2)}")
With expandtabs method: H e l l o
8. find()
Returns the lowest index in the string where substring sub is found within the slice. Optional arguments start and end are interpreted as in slice notation. Return -1 if the sub is not found.
Example:
>>> fruit = "banana"
>>> print(fruit.find("a"))
1
>>> print(fruit.find("a", 2, 6))
3
>>> print(fruit.find("z"))
-1
9. format()
This method was explained in output formatting method 3.
10. format_map()
Returns a formatted version of string using substitutions from mapping.
Example:
>>> login = {"username":"Dawa", "Password":"Xyz2020!"} # Dictionary
>>> print("{username}'s password is {Password}".format_map(login))
Dawa's password is Xyz2020!
11. index()
Similar to the find() method explained in method number 8. The difference is it raise ValueError when the substring is not found.
Example:
>>> fruit = "banana"
>>> print(fruit.index("n"))
2
>>> print(fruit.index("z"))
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print(fruit.index("z"))
ValueError: substring not found
12. isalnum()
Returns True if the string is alpha-numeric, False otherwise.
Example:
>>> name = "Dawa"
>>> password = "xyz@2020!"
>>> print(name.isalnum())
True
>>> print(password.isalnum())
False
13. isalpha()
Returns True if the string is alphabetic, False otherwise.
Example:
>>> name = "Dawa"
>>> password = "xzy2020"
>>> print(name.isalpha())
True
>>> print(password.isalpha())
False
14. isascii()
Returns True if all characters in the string are ASCII, False otherwise.
Example:
>>> password = "xzy2020"
>>> print(password.isascii())
True
15. isdecimal()
Returns True if the string is a decimal string, False otherwise. A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.
If a character can be used to form a number in base 10, then it’s considered a decimal character.
Example:
>>> white = "#FFFFFF" # Hexadecimal code for color white
>>> n = "100"
>>> print(white.isdecimal())
False
>>> print(n.isdecimal())
True
16. isdigit()
Returns True if the string is a digit string, False otherwise. A string is a digit string if all characters in the string are digits and there is at least one character in the string.
Example:
>>> year = "2020"
>>> password = "xzy2020"
>>> print(year.isdigit())
True
>>> print(password.isdigit())
False
17. isidentifier()
Returns True if the string is a valid Python identifier, False otherwise.
Example:
>>> animal = "cat"
>>> print(animal.isidentifier())
True
18. islower()
Returns True if the string is lowercase, False otherwise. A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.
Example:
>>> fname = "dawa"
>>> mname = "Dorji"
>>> lname = "WANGCHUK"
>>> print(fname.islower())
True
>>> print(mname.islower())
False
>>> print(lname.islower())
False
19. isnumeric()
Returns True if the string is numeric, False otherwise. A string is numeric if all characters in the string are numeric and there is at least one character in the string.
Example:
>>> year = "2020"
>>> pd = "plm2020"
>>> print(year.isnumeric())
True
>>> print(pd.isnumeric())
False
20. isprintable()
Returns True if the string is printable, False otherwise. A string is printable if all of its characters are considered printable in repr() or if it is empty.
Example:
>>> site = "Bhutan Python Coders"
>>> site1 = "Bhutan \n Python \n Coders"
>>> site2 = " "
>>> print(site.isprintable())
True
>>> print(site1.isprintable()) # \n(newline) is not printable
False
>>> print(site2.isprintable())
True
21. isspace()
Returns True if the string is a whitespace string, False otherwise. A string is a whitespace if all characters in the string are whitespace and there is at least one character in the string.
Example:
>>> site = "Bhutan Python Coders"
>>> print(site.isspace())
False
>>> name = " "
>>> print(name.isspace())
True
22. istitle()
Returns True if the string is title-cased, False otherwise.
Example:
>>> site = "Bhutan Python Coders"
>>> print(site.istitle())
True
>>> animal = "cow"
>>> print(animal.istitle())
False
23. isupper()
Returns True if the string is uppercase, False otherwise.
Example:
>>> animal = "COW"
>>> animal2 = "cat"
>>> print(animal.isupper())
True
>>> print(animal2.isupper())
False
24. join()
Concatenate any number of strings. The string whose method is called is inserted in between each given string. The result is returned as a new string.
Example:
>>> dzongkhag = ['Paro', 'Thimphu', 'Zhemgang', 'Bumthang']
>>> print("#".join(dzongkhag))
Paro#Thimphu#Zhemgang#Bumthang
25. ljust()
Returns a left-justified version of the string. Padding is done using the specified fill (optional) character (default is a space).
Example:
>>> dzongkhag = "Tashigang"
>>> print(dzongkhag.ljust(12, "#"))
Tashigang###
26. lower()
Returns a copy of the string converted to lowercase.
Example:
>>> site = "Bhutan Python Coders"
>>> print(site.lower())
bhutan python coders
27. lstrip()
Returns a copy of the string with the leading whitespace removed.
Example:
>>> var = " this is string"
>>> print(var.lstrip())
this is string
28. maketrans()
This method was well explained here.
29. partition()
Partition the string into three parts using the given separator. This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.
Example:
>>> ip = "192.168.1.7"
>>> print(ip.partition("."))
('192', '.', '168.1.7')
If the separator is not found, returns a 3-tuple containing the original string
and two empty strings.
Example:
>>> ip = "192.168.1.7"
>>> print(ip.partition("#"))
('192.168.1.7', '', '')
30. replace()
Returns a copy with all occurrences of substring old replaced by new.
Example:
>>> url = "www.bhutanpythoncoders.com"
>>> print(url.replace("com", "org"))
www.bhutanpythoncoders.org
The count is the maximum number of occurrences to replace. -1 (the default value) means to replace all occurrences.
Example:
>>> name = "Dawa"
>>> print(name.replace("a", "e",1))
Dewa
>>> print(name.replace("a", "e", -1))
Dewe
31. rfind()
Returns the highest index in the string where substring sub is found, such that sub is contained within string[start: end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
Example:
>>> site = "BhutanPythonCoders"
>>> print(site.rfind("n"))
11
>>> print(site.rfind("x"))
-1
32. rindex()
Similar to rfind() but raises ValueError when the substring sub is not found.
Example:
>>> site = "BhutanPythonCoders"
>>> print(site.rindex("n"))
11
>>> print(site.rindex("x"))
Traceback (most recent call last):
File "<pyshell#134>", line 1, in <module>
print(site.rindex("x"))
ValueError: substring not found
33. rjust()
Returns a right-justified string of length width. Padding is done using the specified fill character (default is a space).
Example:
>>> animal = "elephant"
>>> print(animal.rjust(10))
elephant
>>> print(animal.rjust(10, "#"))
##elephant
34. rpartition()
Similar to partition() method but returns the 3-tuple in opposite order to partition() method.
Example:
>>> greet = "Good Morning Everyone"
>>> print(greet.rpartition(" "))
('Good Morning', ' ', 'Everyone')
>>> print(greet.partition(" "))
('Good', ' ', 'Morning Everyone')
35. rsplit()
The rsplit() method is very similar to split() function. The only difference is that the splits are done starting at the end of the string. Read about the split() method at method number 37.
36. rstrip()
Returns a copy of the string with trailing whitespace removed from the right or end of the string.
Example:
>>> url = ' www.bhutanpythoncoders.com '
>>> print(url.rstrip())
www.bhutanpythoncoders.com
37. split()
Returns a list of the words in the string, using sep as the delimiter string.
Example:
>>> var = "coding is fun"
>>> print(var.split())
['coding', 'is', 'fun']
If sep is given, consecutive delimiters are not grouped and are deemed to delimit empty strings.
Example:
>>> var1 = '192.168.1.7'
>>> print(var1.split("."))
['192', '168', '1', '7']
38. splitlines()
Returns a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends are given and true.
Example:
>>> n = "I \n love \n python"
>>> print(n.splitlines())
['I ', ' love ', ' python']
>>> print(n.splitlines(keepends = True))
['I \n', ' love \n', ' python']
39. startswith()
Returns True if the string starts with the specified prefix, False otherwise.
Example:
>>> var = "I love python"
>>> print(var.startswith("I"))
True
>>> print(var.startswith("p"))
False
It also takes an optional start and ends argument to compare a string at a particular position.
Example:
>>> var = "I love python"
>>> print(var.startswith("p",7,12))
True
40. strip()
Returns a copy of the string with leading and trailing whitespace removed.
Example:
>>> url = ' www.bhutanpythoncoders.com '
>>> print(url.strip())
www.bhutanpythoncoders.com
It also takes a char argument specifying the set of characters to be removed.
Example:
>>> url = '$www.bhutanpythoncoders.com!'
>>> print(url.strip("$,!"))
www.bhutanpythoncoders.com
41. swapcase()
Converts uppercase characters to lowercase and lowercase characters to uppercase.
Example:
>>> var = "I love PYTHON"
>>> print(var.swapcase())
i LOVE python
42. title()
Returns a title-cased version of the string where words start with an uppercase character and the remaining characters are lowercase.
Example:
>>> var = "learning PYTHON made EASY!"
>>> print(var.title())
Learning Python Made Easy!
43. translate()
44. upper()
Returns a copy of the string converted to uppercase.
Example:
>>> var = "learning PYTHON made EASY!"
>>> print(var.upper())
LEARNING PYTHON MADE EASY!
45. zfill()
Adds a numeric string with zeros on the left, to fill a field of the given width. The string is never truncated.
Example:
>>> num = "101011"
>>> print(num.zfill(10))
0000101011