Tutorials Tonight
Follow Us

List Of 45 Python String Methods


In this tutorial, we will briefly look at the 45 Python string methods. We will see their basic usage with examples. We will also see how to use them in a program.

python string methods

Table Of Contents - Python String Methods


  1. capitalize() Method
  2. casefold() Method
  3. center() Method
  4. count() Method
  5. encode() Method
  6. decode() Method
  7. startswith() Method
  8. endswith() Method
  9. expandtabs() Method
  10. find() Method
  11. rfind() Method
  12. format() Method
  13. format_map() Method
  14. index() Method
  15. rindex() Method
  16. isalnum() Method
  17. isalpha() Method
  18. isdecimal() Method
  19. isdigit() Method
  20. isidentifier() Method
  21. islower() Method
  22. isnumeric() Method
  23. isprintable() Method
  24. isspace() Method
  25. istitle() Method
  26. isupper() Method
  27. join() Method
  28. ljust() Method
  29. rjust() Method
  30. lower() Method
  31. lstrip() Method
  32. rstrip() Method
  33. strip() Method
  34. maketrans() Method
  35. translate() Method
  36. partition() Method
  37. rpartition() Method
  38. replace() Method
  39. split() Method
  40. rsplit() Method
  41. splitlines() Method
  42. swapcase() Method
  43. title() Method
  44. upper() Method
  45. zfill() Method

1. Python String capitalize Method

The capitalize() method capitalizes the first character of each word in a string on which it is applied.

It also converts the other characters of the string to lower case.

str = "hello WORLD"

print(str.capitalize())

Output:

Hello World

You can see the first letter of the string is capitalized and the rest of the string is converted to lower case.

Use of capitalize() Method

You can use to convert all the first letters of any sentence to capital letters. Just split the sentence at space and apply the capitalize() method to each word.

str = "learning python with tutorials tonight"

words = str.split(" ")
# call capitalize() method on each word
for word in words:
    print(word.capitalize())

Output:

Learning Python With Tutorials Tonight

2. Python String casefold Method

The casefold() method converts the string into lower case.

It is similar to the lower() method but casefold() method identifies the UNICODE characters in a string and is better than the lower() method for comparing strings.

str = "Hello World"

# convert string to lower case
print(str.casefold())

Output:

hello world

You can see the string is converted to lower case.

Use of casefold() Method

You can use it when you need to compare 2 strings in a case-insensitive manner. Just apply casefold() method to both the strings and compare them.

str1 = "HeLlO WoRld"
str2 = "hello world"

# compare
if str1.casefold() == str2.casefold():
    print("Strings are equal")
else:
    print("Strings are not equal")

Output:

Strings are equal

3. Python String center Method

The center() method is a visual method that creates a center effect when the string is printed.

It creates equal padding to the left and right sides of the string on which it is applied.

The default padding character is a space. However, you can specify the padding character as well.

str = "python"

# center the string in character of length 10
print(str.center(10))

# center in character of 16
print(str.center(16))

Output:

  python  
     python     

You can also change the padding character by passing the padding character as a second argument to the center() method.

str = "python"

# - as padding character
print(str.center(10, "-"))

Output:

--python--

4. Python String count Method

The count() method counts the number of occurrences of a specified substring in a string.

It returns an integer value if the substring is found in the string. otherwise, it returns 0.

str = "To do or not to do"

# count 'do'
print(str.count("do"))

Output:

2

You can also specify the start and end index of the substring to be counted as 2nd and 3rd arguments respectively.

str = "To do or not to do"

# count 'do' from index 5 to index 20
print(str.count("do", 5, 20))

Output:

1

5. Python String encode Method

The encode() method encodes a given string into a specified encoding. The default encoding is UTF-8.

It returns a byte string.

str = '© ƣ Ƥ Ʀ Ƭ'

# change encoding to utf-8
encoded = str.encode()
print(encoded)

Output:

b'\xc2\xa9 \xc6\xa3 \xc6\xa4 \xc6\xa6 \xc6\xac'

The encode() method accepts error as the second argument. It is used to handle the error that occurs while encoding the string.

ErrorDescription
'backslashreplace'Replace the character with a backslash if it is not supported by the encoding.
'strict'Raises a UnicodeEncodeError exception.
'replace'Replaces the characters that can't be encoded with ?.
'ignore'Ignores the characters that can't be encoded.
'namereplace'Replaces the characters that can't be encoded with their names.
'xmlcharrefreplace'Replaces the characters with XML character references.
str = 'Copyright © ƣ python'

# encode string to ascii
encoded1 = str.encode('ascii', 'backslashreplace')
print(encoded1)

encoded2 = str.encode('ascii', 'replace')
print(encoded2)

encoded3 = str.encode('ascii', 'ignore')
print(encoded3)

encoded4 = str.encode('ascii', 'xmlcharrefreplace')
print(encoded4)

Output:

b'Copyright \\xa9 \\u01a3 python'
b'Copyright ? ? python'
b'Copyright   python'
b'Copyright © ƣ python'

6. Python String decode Method

Just like the encoding method Python has a decoding method that decodes a given byte string into a string.

The decode() method decodes a given byte string into a specified encoding. The default encoding is UTF-8. It reverses the encoding of encode() method.

str = b'\xc2\xa9 \xc6\xa3 \xc6\xa4 \xc6\xa6 \xc6\xac'

# decode string to utf-8
decoded = str.decode()
print(decoded)

Output:

© ƣ Ƥ Ʀ Ƭ

7. Python String startswith Method

The startswith() method checks whether the string starts with the specified substring. It returns True if the string starts with the specified substring, otherwise it returns False.

Syntax:

str.startswith(substr, [start], [end])

The startswith() method accepts substring as the first argument, start and end as optional arguments. They are used to specify the start and end index of the substring to be checked.

str = "To do or not to do"

# check if string starts with 'To'
print(str.startswith("To"))

Output:

True

Use of startswith() method

You can use startswith() method smartly to count the number of occurrences of a substring in a string.

To do this use for loop to iterate over the string and use startswith() method to check if the substring starts with the current character.

str = "To do or not to do"

# count 'do'
count = 0
for i in range(len(str)):
    if str.startswith("do",i):
        count += 1
print(count)

Output:

2

8. Python String endswith Method

The endswith() method checks whether the string ends with a given string. If the string ends with the given string, it returns True, otherwise, it returns False.

Syntax:

str.endswith(substr, [start], [end])

Let's see an example of endswith() method.

str = "To do or not to do"

output = str.endswith("do")
print(output)

output = str.endswith("to do")
print(output)

output = str.endswith("do do")
print(output)

Output:

True
True
False

9. Python String expandtabs Method

The expandtabs() method expands all tab characters (\t) in a string to spaces. The default number of spaces per tab is 8.

However, you can specify the number of spaces per tab by passing the number of spaces as an argument to the expandtabs() method.

str = "Tic\tTic\tTic"

output = str.expandtabs()
print(output)

Output:

Tic     Tic     Tic

Passing 4 as an argument to expandtabs() method will expand all tab characters to 4 spaces.

str = "Tic\tTic\tTic"

output = str.expandtabs(4)
print(output)

Output:

Tic Tic Tic

10. Python String find Method

The find() method searches for the first occurrence of the specified value in the string and returns the index value where it was found.

If the value is not found, it returns -1.

Syntax:

str.find(substr, [start], [end])

The find() method accepts substring as the first argument, start and end are the optional arguments to specify the start and end index of the substring to be searched.

str = "To do or not to do"

# find 'do'
output = str.find("do")
print(output)

Output:

4

You can see the method returns the index of the first occurrence of the substring in the string.

Changing search area within the string by setting start and end arguments.

str = "To do or not to do"

# find 'do' within index 5 to 18
output = str.find("do", 5, 18)
print(output)

Output:

16

11. Python String rfind() Method

The rfind() method returns the last index of the substring in the string, unlike the find() method which returns the first index of the substring.

The rfind() method returns -1 if the substring is not found in the string.

Same like the find() method you can pass the start and endpoint as 2nd and 3rd arguments.

str = "To do or not to do"

index = str.rfind("do")
print(f'Last index of "do" is {index}')

Output:

Last index of "do" is 16

12. Python String format Method

The format() method is used to format a string using the specified arguments.

It accepts a string containing the placeholders for the arguments and returns a formatted string.

The placeholders are specified using the {} syntax.

str = "price of {} is {}"

output = str.format("apple", "Rs.100")
print(output)

Output:

price of apple is Rs.100

The order of the arguments passed to the format() method must match the order of the placeholders in the string.

You can pass numbers in the placeholders to position the arguments in the string.

str = "price of {0} is {1}"

output = str.format("apple", "Rs.100")
print(output)

Output:

price of apple is Rs.100

You can also use names of the arguments as placeholders.

str = "price of {item} is {price}"

output = str.format(item="apple", price="Rs.100")
print(output)

Output:

price of apple is Rs.100

13. Python String format_map Method

The format_map() method is just like the format() method except that it takes a mapping object like dictionary.

The mapping object is used to access the values of the arguments.

fruit = {"item": "apple", "price": "Rs.100"}

output = "{item} costs {price}".format_map(fruit)
print(output)

Output:

apple costs Rs.100

14. Python String index Method

The index() method is used to find the index of the first occurrence of the specified value in the string.

If the value is not found, it raises a ValueError exception.

Syntax:

str.index(substr, [start], [end])

Here is an example of using the index() method.

str = "To do or not to do"

# find 'do'
output = str.index("do")
print(output)

Output:

4

Note: Both find() and index() methods are same except that find() method returns -1 if the value is not found while index() method raises a ValueError exception.

The following example searches for something that is not present in the string.

str = "To do or not to do"

# find 'cat' in str
try:
    print(str.index("cat"))
except ValueError:
      print("cat not found")

Output:

cat not found

15. Python String rindex() Method

The rindex() method returns the last index of the substring in the string unlike index() method which returns the first index of the substring.

If no match is found then it raises an exception.

str = "To do or not to do"

index = str.rindex("do")
print(f'Last index of "do" is {index}')

Output:

Last index of "do" is 16

16. Python String isalnum Method

The isalnum() method is used to check if all the characters in the string are alphanumeric means the characters are either a letter or a digit.

The isalnum() method returns True if all the characters in the string are alphanumeric and False otherwise.

In the terms of regex it is equal to [a-zA-Z0-9].

str = "User123"
print(str.isalnum())

str = "User 123"
print(str.isalnum())

Output:

True
False

17. Python String isalpha Method

The isalpha() method is used to check if all the characters in the string are alphabetic means the characters are letters. Example "ABCabc" is alphabetic while "ABC123" is not.

The isalpha() method returns True if all the characters in the string are alphabetic and False otherwise.

In the terms of regex, it is equal to [a-zA-Z].

str = "AgsKfvBvCaHEbc"
print(str.isalpha()) # True

str = "AgsKfvBvCaHEbc123"
print(str.isalpha()) # False

str = "ABC abc"
print(str.isalpha()) # False

Output:

True
False
False

18. Python String isdecimal Method

The isdecimal() method is used to check if all the characters in the string are only digits, like 01234, ०१२३४, 𝟘𝟙𝟚𝟛𝟜, ٠١٢٣٤, etc.

The method returns True if all the characters in the string are digits and False if not.

Fractional numbers, superscript, subscript, and other symbols are not considered digits. For example, 0.1, ½, ⁰¹², ₀₁₂, etc. are not considered digits.

str = "01234"
print(str.isdecimal()) # True

str = "०१२३४"
print(str.isdecimal()) # True

str = "𝟘𝟙𝟚𝟛𝟜"
print(str.isdecimal()) # True

str = "ⅰⅱⅲ"
print(str.isdecimal()) # False

str = "½⅓"
print(str.isdecimal()) # False

str = "12a3"
print(str.isdecimal()) # False

Output:

True
True
True
False
False
False

19. Python String isdigit Method

The isdigit() method is used to check if all the characters in the string are digits, like 12345, ०१२३४, ⁰¹²³⁴, ₀₁₂₃₄, ⓿❶❷❸❹, etc.

Superscripts, subscripts are considered as digits but fractional numbers, other symbols are not considered as digits.

str = "01234"
print(str.isdigit()) # True

str = "०१२३४"
print(str.isdigit()) # True

str = "⁰¹²³⁴"
print(str.isdigit()) # True

str = "₀₁₂₃₄"
print(str.isdigit()) # True

str = "➊➋➌➍➎"
print(str.isdigit()) # True

str = "½⅓"
print(str.isdigit()) # False

str = "12a3"
print(str.isdigit()) # False

Output:

True
True
True
True
True
False
False

20. Python String isidentifier Method

The isidentifier() method is used to check if the string is a valid identifier. An identifier is a name that can be used as a variable name, function name, or any other name.

The method returns True if the string is a valid identifier and False if not.

This Python string method can be used to check if the string is a valid variable name, function name, or any other name in Python.

str = "my_name"
print(str.isidentifier()) # True

str = "my name"
print(str.isidentifier()) # False

str = "name123"
print(str.isidentifier()) # True

str = "123name"
print(str.isidentifier()) # False

Output:

True
False
True
False

21. Python String islower Method

The islower() method checks if all the characters in the string are lowercase letters.

The method returns True if all the characters in the string are lowercase letters and False if not.

str = "learning python"
print(str.islower()) # True

str = "Learning Python"
print(str.islower()) # False

Output:

True
False

22. Python String isnumeric Method

The isnumeric() method checks if all the characters in the string are numeric characters.

Anything that makes sense as a number, like fraction (½⅓¼), superscript (⁰¹²³⁴), subscript (₀₁₂₃₄), Romans (ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯ), etc. are considered as numeric characters.

The method returns True if all the characters in the string are numeric characters and False if not.

str = "01234"
print(str.isnumeric()) # True

str = "०१२३४"
print(str.isnumeric()) # True

str = "⁰¹²³⁴"
print(str.isnumeric()) # True

str = "ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩⅪⅫⅬⅭⅮⅯ"
print(str.isnumeric()) # True

str = "½⅓"
print(str.isnumeric()) # True

str = "12a3"
print(str.isnumeric()) # False

Output:

True
True
True
True
True
False

23. Python String isprintable Method

The isprintable() method checks if all the characters in the string are printable characters.

Printable characters are those that can be printed on the screen. For example, a \n, \t, \r, do not print on the screen (unless escaped by \) so they are not printable.

The method returns True if all the characters in the string are printable characters and False if 1 or more characters are not printable.

str = "Python, Java"
print(str.isprintable()) # True

str = "Python\n no Java"
print(str.isprintable()) # False

Output:

True
False

24. Python String isspace Method

The isspace() method checks if all the characters in the string are whitespace characters.

' ' (space), '\t' (tab), '\n' (newline), '\r' (carriage return), '\f' (form feed), and '\v' (vertical tab) are considered as whitespaces.

isspace() returns True if all the characters in the string are whitespace characters and False if 1 or more characters are not whitespace characters.

str = "   "
print(str.isspace()) # True

str = "\t \n \t    "
print(str.isspace()) # True

str = "   a   \n"
print(str.isspace()) # False

Output:

True
True
False

25. Python String istitle Method

The istitle() method checks if all the words in the string are title cases.

Title case is the case where the first letter of the word is capitalized and the rest of the letters are lowercase.

The method returns True if all the words in the string are title case, else False.

str = "My Name Is"
print(str.istitle()) # True

str = "My name is"
print(str.istitle()) # False

str = "My NAME Is"
print(str.istitle()) # False

str = "My Name Is 123"
print(str.istitle()) # True

Output:

True
False
False
True

26. Python String isupper Method

The isupper() method checks if all the characters in the string are uppercase letters.

If all the characters in the string are uppercase letters, then the method returns True, if any character is lowercase, then the method returns False.

str = "PYTHON IS AWESOME"
print(str.isupper()) # True

str = "Python is AWESOME"
print(str.isupper()) # False

Output:

True
False

27. Python String join Method

The join() method joins the elements of an iterable into a string using the string as a separator.

The method returns a string which is the concatenation of the strings in the iterable. The separator is the string on which the join() method is called.

The iterable that can be used with the methods are list, tuple, set, or dictionary.

joined = "-".join(["Tom", "Jerry", "Harry"])
print(joined) # Tom-Jerry-Harry

joined = " ".join(["Tom", "Jerry", "Harry"])
print(joined) # Tom Jerry Harry

joined = ",".join(["Tom", "Jerry", "Harry"])
print(joined) # Tom,Jerry,Harry

Output:

Tom-Jerry-Harry
Tom Jerry Harry
Tom,Jerry,Harry

28. Python String ljust Method

The ljust() method returns a string of the specified length, replacing the remaining characters with the specified fill character on the right side of the string.

For example, if the string is "Python" and the length is 10, and the fill character is "*", then the method returns "Python****".

If the length of the string is less than the specified length, then the method returns the string itself.

str = "Python"
print(str.ljust(10, "*")) # Python*****

print(str.ljust(5, "*")) # Python

print(str.ljust(12, "#")) # Python######

Output:

Python*****
Python
Python######

29. Python String rjust Method

The rjust() method returns a string of the specified length, replacing the remaining characters with the specified fill character on the left side of the string.

For example, if the string is "Python" and the length is 10, and the fill character is "*", then the method returns "*****Python".

Just like ljust method if the length of the string is less than the specified length, then the method returns the string itself.

str = "Python"
print(str.rjust(10, "*")) # ****Python

print(str.rjust(5, "*")) # Python

print(str.rjust(12, "#")) # #########Python

Output:

****Python
Python
######Python

30. Python String lower Method

The lower() method returns a copy of the string in lower case.

The method does not modify the original string.

str = "PYTHON IS AWESOME"
print(str.lower()) # python is awesome

str = "PyTHon3 I5 Awe50m3"
print(str.lower()) # python3 i5 awe50m3

Output:

python is awesome
python3 i5 awe50m3

31. Python String lstrip Method

The lstrip() method returns a copy of the string after removing specified characters from the left side of the string. If the characters are not specified, then the method removes whitespace from the left side of the string.

str = "   Python is awesome   "
print(str.lstrip()) # 'Python is awesome   '

str = "****Python is awesome****"
print(str.lstrip("*")) # Python is awesome****

Output:

Python is awesome   
Python is awesome****

The lstrip() method not just removes a single character but it removes any combination of mentioned characters from the left which is mentioned.

For example, if the mentioned character to remove is "+*#" then any combination of these 3 characters before the introduction of another character will be removed. Like ++**##Python -> Python, +*#+*#Python -> Python, #+##***+#*Python -> Python, etc.

str = "+*#Python"
print(str.lstrip("+*#")) # Python

str = "++**##Python"
print(str.lstrip("+*#*")) # Python

str = "+*#+*#Python"
print(str.lstrip("+*#*")) # Python

str = "#+##***+#*Python"
print(str.lstrip("+*#*")) # Python

Output:

Python
Python
Python
Python

32. Python String rstrip Method

The rstrip() method returns a copy of the string after removing specified characters from the right side of the string. If no characters are specified, then whitespaces are removed from the right side of the string.

str = "   Python is awesome   "
print(str.rstrip()) #   Python is awesome

str = "****Python is awesome****"
print(str.rstrip("*")) # ****Python is awesome

Output:

   Python is awesome
****Python is awesome

The rstrip() method removes any combination of mentioned characters from the right which is mentioned.

For example, if the mentioned character to remove is "+*#" then any combination of these 3 characters from the right side of the string will be removed. Like Python++**## -> Python, Python+*#+*# -> Python, etc.

str = "Python+*#"
print(str.rstrip("+*#")) # Python

str = "Python++**##"
print(str.rstrip("+*#*")) # Python

str = "Python+*#+*#"
print(str.rstrip("+*#*")) # Python

str = "Python#+##***+#*"
print(str.rstrip("+*#*")) # Python

Output:

Python
Python
Python
Python

33. Python String strip Method

The strip() method works exactly like lstrip() and rstrip() method, but it removes whitespaces, characters, or combinations of characters from both the left and right sides of the string.

str = "   Python is awesome   "
print(str.strip()) #   Python is awesome

str = "****Python is awesome****"
print(str.strip("*")) # ****Python is awesome

str = "+*#Python+*#"
print(str.strip("+*#")) # Python

str = "++**##Python++**##"
print(str.strip("+*#*")) # Python

str = "+*#+*#Python+*#+*#"
print(str.strip("+*#*")) # Python

str = "##***+Python#+##***+#*"
print(str.strip("+*#*")) # Python

Output:

Python is awesome
Python is awesome
Python
Python
Python
Python

34. Python String maketrans Method

The maketrans() method returns a translation table that can be used to convert a string into another string.

The method is used to create a map to replace a character in a string with some other character or delete a character from a string.

The method takes 3 arguments:

  1. toReplace - The characters to be replaced.
  2. replacement - The replacement characters.
  3. delete - The characters to be deleted.
str = "To do or not to do"

map_table = str.maketrans("o", "a", "d")

This method is fully functioning when used with the translate() method.


35. Python String translate() Method

The translate() method replaces the characters in the string using the specified translation table created by maketrans() method.

Pass the translation table as an argument to the translate() method and it will replace the characters in the string using the translation table.

str = "To do or not to do"

map_table = str.maketrans("o", "a", "d")

output = str.translate(map_table)
print(output)

Output:

Ta a ar nat ta a

36. Python String partition() Method

The partition() method finds a specified substring and splits the string into 3 parts: the part before the 1st match, the 2nd part is the match itself and the 3rd part is the part after the match.

After splitting the string into 3 parts it returns a tuple containing the 3 parts.

If there is no match then the method returns the string as 1st part and empty string as 2nd and 3rd part.

str = "To do or not to do"

output = str.partition("not")
print(output)

output = str.partition("cat")
print(output)

Output:

('To do or ', 'not', ' to do')
('To do or not to do', '', '')

37. Python String rpartition() Method

The rpartition() method finds the last occurrence of the substring and splits the string into 3 parts: the part before the match, the match itself, and the part after the match.

The method returns a tuple containing these 3 parts.

In case of no match found then the method returns the string as 1st part and empty string as 2nd and 3rd part.

str = "To do or not to do"

output = str.rpartition("to")
print(output)

Output:

('To do or not ', 'to', ' do')

38. Python String replace() Method

The replace() method is a Python built-in method that replaces a string with another string.

The method takes 3 arguments:

  1. old - The characters to be replaced.
  2. new - The replacement characters.
  3. count - The number of occurrences to be replaced. By default, it is -1 which means replacing all occurrences.
str = "To do or not to do"

output = str.replace("do", "run")
print(output)

# replace only 1 occurrence
output = str.replace("do", "run", 1)
print(output)

Output:

To run or not to run
To run or not to do

39. Python String split() Method

Among all Python string methods, the split() method splits the string into substrings at the given separator and returns a list of substrings.

Syntax:

str.split(sep, maxsplit)

The method takes separator as the first argument and the number of splits as the second argument.

str = "To do or, not to do"
print(str.split()) # split at space

print(str.split(",")) # split at ,

Output:

['To', 'do', 'or,', 'not', 'to', 'do']
['To do or', ' not to do']

40. Python String rsplit() Method

The rsplit() method is the same as split() method but it splits the string from right to left. But the list generated is not in reverse order.

Syntax:

str.rsplit(sep, maxsplit)

Here is example of rsplit() method:

str = "To do or, not to do"
print(str.rsplit()) # split at space

print(str.rsplit(",")) # split at ,

Output:

['To', 'do', 'or,', 'not', 'to', 'do']
['To do or', ' not to do']

You would be what difference does it makes to the split() method?

The difference is only visible when you use maxsplit argument.

str = "To do or not to do"
      
print(str.split(' ', 2))
print(str.rsplit(' ', 2))

Output:

['To', 'do', 'or not to do']
['To do or not', 'to', 'do']

41. Python String splitlines() Method

The splitlines() method splits the string into lines and returns a list of lines.

The method takes one optional argument which is a boolean value. If it is True then the newline characters are also included in the list. By default it is False.

str = "To do or\n not to do"
print(str.splitlines())

print(str.splitlines(True))

Output:

['To do or', ' not to do']
['To do or\n', ' not to do']

42. Python String swapcase() Method

The swapcase() method swaps the case of all the characters in the string.

The uppercase characters are converted to lowercase and vice versa.

str = "To Do OR noT tO DO"

print(str.swapcase())

Output:

tO dO or NOt To do

43. Python String title() Method

The title() method returns a title-cased version of the string.

The first letter of each word is capitalized and the rest of the letters are lowercase.

str = "to do or not to do"

print(str.title())

Output:

To Do Or Not To Do

44. Python String upper() Method

The upper() method returns a copy of the string in which all the lowercase letters are converted to uppercase.

str = "to do or not to do"

print(str.upper())

Output:

TO DO OR NOT TO DO

45. Python String zfill() Method

The zfill() method returns a string with the digits filled in from the left with zeros.

For example, if the length of the string is 5 and we zfill() it with a length of 10, then the string will be padded with 5 zeros from the left. If the length of the string is already 10 or greater than 10, then it will be returned as it is.

str = "hello"
print(str.zfill(10))

str = "hello world"
print(str.zfill(10))

str = "55.28"
print(str.zfill(10))

Output:

00000hello
hello world
0000055.28

Conclusion

In this complete guide of Python string methods, we have completed all the string methods in Python with their use, explanation, and example.

Now you can use all the string methods in Python with your own string.