Python String Methods

Python String Methods

Python string class has a set of methods, which we can use on String objects.

In this tutorial, we shall go through each of the method, what it does, and how to use it in a program.

1. capitalize()

Python string capitalize() method converts the first character in the string to uppercase, and returns the resulting string. Original string is unmodified.

Tutorial : Python String capitalize()

In the following program, we take a string in variable x, and capitalize the string using String capitalize() method.

Python Program

x = "hello world"
result = x.capitalize()
print(f"Given string       : {x}")
print(f"Capitalized string : {result}")
Run Code Copy

Output

Given string       : hello world
Capitalized string : Hello world

2. casefold()

Python String casefold() method converts the given string to lowercase, and returns the resulting string. Original string is unmodified.

Tutorial : Python String casefold()

In the following program, we take a string in variable x, and convert the string to lowercase using String casefold() method.

Python Program

x = "HELLO World"
result = x.casefold()
print(f"Given string     : {x}")
print(f"Casefold string  : {result}")
Run Code Copy

Output

Given string     : HELLO World
Casefold string  : hello world

3. center()

Python String center() method centers a given string in a specified length, with an optional fill character placed at the edges, and return the resulting string.

Tutorial : Python String center()

In the following program, we take a string in variable x, and center the string to a resulting length of 21 with fill character “-“ using String center() method.

Python Program

x = "Hello World"
result = x.center(21, "-")
print(f"Given string    : \"{x}\"")
print(f"Centered string : \"{result}\"")
Run Code Copy

Output

Given string    : "Hello World"
Centered string : "-----Hello World-----"

4. count()

Python String count() method counts the number of occurrences of a value in the string, and return the count value as integer.

Tutorial : Python String count()

In the following program, we take a string in variable x, and count the number of occurrences of the value “Hello” using String count() method. We shall store the count() returned value in result variable.

Python Program

x = "Hello World! Hello User!"
result = x.count("Hello")
print(f"Count : {result}")
Run Code Copy

Output

Count : 2

5. encode()

6. endswith()

Python String endswith() method is used to check if the string ends with a specified suffix string.

Tutorial : Python String endswith()

In the following program, we take a string in variable x, and check if this string ends with the value “world” using String endswith() method.

Python Program

x = "hello world"
if x.endswith("world"):
    print("The string ENDS with specified value.")
else:
    print("The string DOES NOT END with specified value.")
Run Code Copy

Output

The string ENDS with specified value.

7. expandtabs()

8. find()

Python String find() method finds the index of first occurrence of a specific value in given string, and returns it as an integer value. Returns -1 if the value is not found in the string.

Tutorial : Python String find()

In the following program, we take a string in variable x, and find the index of first occurrence of the value “apple” in the string using String find() method.

Python Program

x = "Some apples are red."
result = x.find("apple")
print(f"Index : {result}")
Run Code Copy

Output

Index : 5

9. format()

10. format_map()

11. index()

Python index() method finds the index of first occurrence of a specific value in given string, and returns it as an integer value. Raises ValueError if the value is not found in the string.

Tutorial : Python String index()

In the following program, we take a string in variable x, and find the index of first occurrence of the value “apple” in the string using String index() method.

Python Program

x = "Some apples are red. Some apples are good."
result = x.index("apple")
print(f"Index : {result}")
Run Code Copy

Output

Index : 5

12. isalnum()

Python String isalnum() method is used to check if all characters in the string are alphanumeric(alphabets and numeric) characters and there is at least one character in the string.

Tutorial : Python String isalnum()

In the following example, we take a string value in variable x and check if all characters in the string are alphanumeric.

Python Program

x = "Abc123456"

if x.isalnum():
    print('Given string is ALPHA-NUMERIC.')
else:
    print('Given string is NOT ALPHA-NUMERIC.')
Run Code Copy

Output

Given string is ALPHA-NUMERIC.

13. isalpha()

Python String isalpha() method is used to check if all characters in the string are alphabets and there is at least one character in the string.

Tutorial : Python String isalpha()

In the following example, we take a string value in variable x, and we shall check if all characters in the string are alphabets.

Python Program

x = "HelloWorld"

if x.isalnum():
    print('Given string is ALPHABETIC.')
else:
    print('Given string is NOT ALPHABETIC.')
Run Code Copy

Output

Given string is ALPHABETIC.

14. isascii()

Python String isascii() method is used to check if the string is empty or if all characters in the string are ASCII.

Tutorial : Python String isascii()

In this example, we take a string value in variable x, and we shall check if all characters in the string are ASCII.

Python Program

x = "Hello World"

if x.isascii():
    print('Given string is ASCII.')
else:
    print('Given string is NOT ASCII.')
Run Code Copy

Output

Given string is ASCII.

15. isdecimal()

Python String isdecimal() method is used to check if all characters in the string are decimal characters and there is at least one character in the string.

Tutorial : Python String isdecimal()

In the following example, we take a string value in variable x, and check if all characters in the string are decimal.

Python Program

x = "12345"

if x.isdecimal():
    print('Given string is DECIMAL.')
else:
    print('Given string is NOT DECIMAL.')
Run Code Copy

Output

Given string is DECIMAL.

16. isdigit()

Python String isdigit() method is used to check if all characters in the string are digits and there is at least one character in the string.

Tutorial : Python String isdigit()

In the following example, we take a string value in variable x and check if the string contains only digits.

Python Program

x = "12345"

if x.isdigit():
    print('Given string is DIGIT.')
else:
    print('Given string is NOT DIGIT.')
Run Code Copy

Output

Given string is DIGIT.

17. isidentifier()

Python String isidentifier() method is used to check if the string is a valid identifier according to Python language.

Tutorial : Python String isidentifier()

In this example, we take a string value "value_1" in variable x. We have to check if this string is a valid identifier.

Python Program

x = "value_1"

if x.isidentifier():
    print('Given string is a valid IDENTIFIER.')
else:
    print('Given string is NOT a valid IDENTIFIER.')
Run Code Copy

Output

Given string is a valid IDENTIFIER.

18. islower()

Python String islower() method is used to check if all cased characters in the string are lower case.

Tutorial : Python String islower()

In the following program, we take a string value in variable x and check if all cased characters in the string are lower case.

Python Program

x = "hello world"

if x.islower():
    print('Given string is LOWER CASE.')
else:
    print('Given string is NOT LOWER CASE.')
Run Code Copy

Output

Given string is LOWER CASE.

19. isnumeric()

Python String isnumeric() method is used to check if all characters in the string are numeric characters and there is at least one character in the string.

Tutorial : Python String isnumeric()

In the following program, we take a string value in variable x and check if all characters in the string are numeric.

Python Program

x = "123456"

if x.isnumeric():
    print('Given string is NUMERIC.')
else:
    print('Given string is NOT NUMERIC.')
Run Code Copy

Output

Given string is NUMERIC.

20. isprintable()

21. isspace()

Python String isspace() method is used to check if all characters in the string are whitespace characters and there is at least one character.

Tutorial : Python String isspace()

In the following program, we take a string value in variable x and check if all characters in the string are all whitespace characters.

Python Program

x = "    \t\n"

if x.isspace():
    print('Given string is SPACE.')
else:
    print('Given string is NOT SPACE.')
Run Code Copy

Output

Given string is SPACE.

22. istitle()

Python String istitle() method returns True if all the words in the given text start with an upper case and the rest of the characters in the words are lower case, or False otherwise.

Tutorial : Python String istitle()

In this example, we take a string value in variable x. We have to check if the text in this string is a title or not.

Python Program

x = "Hello World"

if x.istitle():
    print('Given string is a TITLE.')
else:
    print('Given string is NOT a TITLE')
Run Code Copy

Output

Given string is a TITLE.

23. isupper()

Python String isupper() method is used to check if all cased characters in the string are upper case.

Tutorial : Python String isupper()

In the following program, we take a string value in variable x and check if all cased characters in the string are uppercase.

Python Program

x = "HELLO WORLD"

if x.isupper():
    print('Given string is UPPER CASE.')
else:
    print('Given string is NOT UPPER CASE.')
Run Code Copy

Output

Given string is UPPER CASE.

24. join()

Python String join() method joins the strings in the given iterable by the separator string and returns the resulting string.

Tutorial : Python String join()

In the following program, we take a list with four strings, and join these strings with '--' as separator.

Python Program

my_list = ['apple', 'banana', 'cherry']
result = '--'.join(my_list)
print(result)
Run Code Copy

Output

apple--banana--cherry

25. ljust()

26. lower()

Python String lower() method is used to convert all the cased characters in the string to lower case.

Tutorial : Python String lower()

In the following program, we take a string in variable x. We have to covert this string to lower case.

Python Program

x = "HELLO World!"
x_lower = x.lower()
print(f"Lower string : {x_lower}")
Run Code Copy

Output

Lower string : hello world!

27. lstrip()

Python String lstrip() method returns a string with the whitespaces or specified characters removed from the starting/left-side of given string.

Tutorial : Python String lstrip()

In the following program, we take a string, and strip whitespace characters from the left side of the string.

Python Program

# Given string
x = "  hello world    "

# Strip whitespaces on left side of string
x_stripped = x.lstrip()

print(f"Original      : \"{x}\"")
print(f"Left Stripped : \"{x_stripped}\"")
Run Code Copy

Output

Original      : "  hello world    "
Left Stripped : "hello world    "

28. maketrans()

Python String maketrans() method is used to create a mapping table which can be used with the string translate() method. translate() method replaces specific characters in the string based on the mapping table.

Tutorial : Python String maketrans()

In the following program, we shall create a mapping table with two characters for argument x, two characters for argument y, and one character for argument z of maketrans() method, and print the mapping table to output.

Python Program

table = str.maketrans('lo', 'pm', 'w')
print(f"Mapping table : {table}")
Run Code Copy

Output

Mapping table : {108: 112, 111: 109, 119: None}

29. partition()

Python String partition() method splits the string at the occurrence of specified separator, and returns a tuple containing the first string part before the split, separator, and the string part after the split.

Tutorial : Python String partition()

In the following program, we take a string value in variable x and partition this string with a separator "-".

Python Program

x = "apple-banana-cherry"

result = x.partition("-")
print(result)
Run Code Copy

Output

('apple', '-', 'banana-cherry')

30. removeprefix()

Python String removeprefix() method removes the specified prefix from the string, if the string starts with the specified prefix, and returns the resulting string.

Tutorial : Python String removeprefix()

In the following example, we are give a string in my_string. In this string, we have to remove the prefix value "Hello" from the string.

Python Program

my_string = "HelloWorld"
output_string = my_string.removeprefix("Hello")
print(output_string)
Run Code Copy

Output

World

31. removesuffix()

Python String removesuffix() method removes the specified suffix from the string, if the string ends with the specified suffix value, and returns the resulting string.

Tutorial : Python String removesuffix()

In the following example, we are given a string in my_string. In this string, we have to remove the suffix value “World” from the string.

Python Program

my_string = "HelloWorld"
output_string = my_string.removesuffix("World")
print(output_string)
Run Code Copy

Output

Hello

32. replace()

Python String replace() method replaces all the occurrences of an old value with a new value in the string.

Tutorial : Python string replace()

In the following example, we are give a string in my_string. In this string, we have to replace the old value "apple" with a new value "fig" using string replace() method.

Python Program

my_string = "apple cherry apple banana"
replaced_string = my_string.replace("apple", "fig")
print(replaced_string)
Run Code Copy

Output

fig cherry fig banana

33. rfind()

34. rindex()

35. rjust()

36. rpartition()

37. rsplit()

38. rstrip()

Python String rstrip() method returns a string with the whitespaces or specified characters removed from the trailing/ending/right-side of given string..

Tutorial : Python String rstrip()

In the following program, we shall strip whitespace characters from the right edge of given string.

Python Program

# Given string
x = "  hello world    "

# Strip whitespaces on right edge of string
x_stripped = x.rstrip()

print(f"Original       : \"{x}\"")
print(f"Right Stripped : \"{x_stripped}\"")
Run Code Copy

Output

Original       : "  hello world    "
Right Stripped : "  hello world"

39. split()

Python String split() method splits the string into parts using given separator string.

Tutorial : Python String split()

In the following example, we take a string that has chunks separated by comma. We will split this string using comma as separator and store the result in a variable.

Python Program

x = 'apple,banana,cherry'

chunks = x.split(',')
print(chunks)
Run Code Copy

Output

['apple', 'banana', 'cherry']

40. splitlines()

Python String splitlines() method splits the given string at line breaks and returns a list.

Tutorial : Python string splitlines()

In the following program, we take a string in variable x, and split the string at line breaks using String splitlines() method.

Python Program

x = "apple\nbanana\ncherry"

lines = x.splitlines()

print(lines)
Run Code Copy

Output

['apple', 'banana', 'cherry']

41. startswith()

Python String startswith() method is used to check if the given string starts with a specific value.

Tutorial : Python String startswith()

In the following program, we take a string in variable x, and check if this string starts with the value “hello” using String startswith() method.

Python Program

x = "hello world"

if x.startswith("hello"):
    print("The string STARTS with specified value.")
else:
    print("The string DOES NOT START with specified value.")
Run Code Copy

Output

The string STARTS with specified value.

42. strip()

Python String strip() method returns a string with the leading (beginning) and trailing (ending) whitespaces or specified characters removed from the given string.

Tutorial : Python String strip()

In the following program, we will strip whitespace characters from the edges of a given string.

Python Program

# Given string
x = "   hello world "

# Strip whitespaces
x_stripped = x.strip()

print(f"Original : \"{x}\"")
print(f"Stripped : \"{x_stripped}\"")
Run Code Copy

Output

Original : "   hello world "
Stripped : "hello world"

43. swapcase()

Python String swapcase() method transforms lower case alphabets to upper case alphabets, and upper case alphabets to lower case alphabets in the given string. The non-alphabetic characters remain unchanged.

Tutorial : Python String swapcase()

In the following program, we take a string value in variable x. We have to swap case of characters in this string.

Python Program

# Take a string
x = "Hello World"

# Swap the case of characters in string
x_result = x.swapcase()

# Print case swapped string
print(x_result)
Run Code Copy

Output

hELLO wORLD

44. title()

Python String istitle() method returns the title representation of the given string. A title is a string in which every first alphabet in the words of the string is an upper case, and rest of the characters are lower case.

Tutorial : Python String title()

In the following program, we take a string value with all lower case characters in variable x. We have to convert this string to a title.

Python Program

# Take a string
x = "hello world"

# Convert to title string
x_title = x.title()

# Print title string
print(x_title)
Run Code Copy

Output

Hello World

45. translate()

Python String translate() method returns a string where some specific characters are replaced with replacement characters. These specific characters and their replacements can be described in a dictionary, or in a mapping table.

Tutorial : Python String translate()

In the following program, we a string in x. We translate this string: replace character l with p, and character o with m, by using a dictionary with these mappings, as argument to the translate() method.

Python Program

# Given string
x = "hello world"

# Define a mapping table
table = {108: 112, 111: 109}

# Translate given string
x_translated = x.translate(table)

print(f"Original   : \"{x}\"")
print(f"Translated : \"{x_translated}\"")
Run Code Copy

Output

Original   : "hello world"
Translated : "heppm wmrpd"

46. upper()

Python String upper() method is used to convert all the cased characters in the string to upper case.

Tutorial : Python String upper()

In the following program, we take a string in variable x. We shall covert this string to upper case.

Python Program

x = "Hello World!"
x_upper = x.upper()
print(f"Given string : {x}")
print(f"Upper string : {x_upper}")
Run Code Copy

Output

Given string : Hello World!
Upper string : HELLO WORLD!

47. zfill()

Code copied to clipboard successfully 👍