Python

Python String Manipulation Functions - Full Reference

Updated 7/2/202613 min readDownload PDFEdit

Python String Manipulation Functions — Full Reference

Every built-in method available on Python's str type, with a description and 2 code examples for each.


1. capitalize()

Returns a copy of the string with the first character capitalized and the rest lowercased.

# Example 1
s = "hello WORLD"
print(s.capitalize())  # Output: "Hello world"
# Example 2
title = "python programming"
print(title.capitalize())  # Output: "Python programming"

2. casefold()

Returns an aggressively lowercased version of the string, used for caseless matching (stronger than lower(), handles special Unicode cases like German ß).

# Example 1
s = "HELLO"
print(s.casefold())  # Output: "hello"
# Example 2
german = "Straße"
print(german.casefold())  # Output: "strasse"

3. center()

Centers the string within a specified width, padding with a character (default is space).

# Example 1
s = "hi"
print(s.center(10))  # Output: "    hi    "
# Example 2
s = "menu"
print(s.center(12, "*"))  # Output: "****menu****"

4. count()

Returns the number of non-overlapping occurrences of a substring.

# Example 1
s = "banana"
print(s.count("a"))  # Output: 3
# Example 2
sentence = "the cat sat on the mat"
print(sentence.count("the"))  # Output: 2

5. encode()

Encodes the string into bytes using the specified encoding (default UTF-8).

# Example 1
s = "hello"
print(s.encode())  # Output: b'hello'
# Example 2
s = "café"
print(s.encode("utf-8"))  # Output: b'caf\xc3\xa9'

6. endswith()

Checks whether the string ends with the specified suffix (or tuple of suffixes).

# Example 1
filename = "report.pdf"
print(filename.endswith(".pdf"))  # Output: True
# Example 2
filename = "photo.png"
print(filename.endswith((".jpg", ".png", ".gif")))  # Output: True

7. expandtabs()

Replaces tab characters (\t) with spaces, up to a specified tab size (default 8).

# Example 1
s = "a\tb\tc"
print(s.expandtabs(4))  # Output: "a   b   c"
# Example 2
s = "name\tage\tcity"
print(s.expandtabs())  # Output: "name    age     city"

8. find()

Returns the lowest index of a substring, or -1 if not found.

# Example 1
s = "hello world"
print(s.find("world"))  # Output: 6
# Example 2
s = "hello world"
print(s.find("xyz"))  # Output: -1

9. format()

Formats a string using placeholders {} filled with the given arguments.

# Example 1
name, age = "Kalyan", 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: "My name is Kalyan and I am 25 years old."
# Example 2
print("{0} scored {1:.2f}%".format("Alice", 92.567))
# Output: "Alice scored 92.57%"

10. format_map()

Similar to format(), but takes a single dictionary/mapping for substitutions.

# Example 1
data = {"name": "Sam", "job": "Engineer"}
print("{name} works as an {job}".format_map(data))
# Output: "Sam works as an Engineer"
# Example 2
class Default(dict):
    def __missing__(self, key):
        return "N/A"

print("City: {city}".format_map(Default(name="Sam")))
# Output: "City: N/A"

11. index()

Like find(), but raises ValueError if the substring is not found.

# Example 1
s = "hello world"
print(s.index("world"))  # Output: 6
# Example 2
s = "hello world"
try:
    print(s.index("xyz"))
except ValueError as e:
    print(f"Error: {e}")  # Output: Error: substring not found

12. isalnum()

Returns True if all characters are alphanumeric (letters or digits) and there is at least one character.

# Example 1
print("Python3".isalnum())  # Output: True
# Example 2
print("Hello World!".isalnum())  # Output: False (space and ! are not alnum)

13. isalpha()

Returns True if all characters are alphabetic and there is at least one character.

# Example 1
print("Hello".isalpha())  # Output: True
# Example 2
print("Hello123".isalpha())  # Output: False

14. isascii()

Returns True if all characters are ASCII.

# Example 1
print("Hello".isascii())  # Output: True
# Example 2
print("café".isascii())  # Output: False

15. isdecimal()

Returns True if all characters are decimal digits (0-9 form only, no superscripts/fractions).

# Example 1
print("12345".isdecimal())  # Output: True
# Example 2
print("12.5".isdecimal())  # Output: False (decimal point not allowed)

16. isdigit()

Returns True if all characters are digits, including some non-decimal digit forms (e.g., superscripts).

# Example 1
print("123".isdigit())  # Output: True
# Example 2
print("²³".isdigit())  # Output: True (superscript digits count)

17. isidentifier()

Returns True if the string is a valid Python identifier (variable name).

# Example 1
print("variable_name".isidentifier())  # Output: True
# Example 2
print("2fast".isidentifier())  # Output: False (cannot start with a digit)

18. islower()

Returns True if all cased characters are lowercase and there is at least one cased character.

# Example 1
print("hello world".islower())  # Output: True
# Example 2
print("Hello World".islower())  # Output: False

19. isnumeric()

Returns True if all characters are numeric, including fractions and Unicode numerals (broader than isdigit()).

# Example 1
print("12345".isnumeric())  # Output: True
# Example 2
print("½".isnumeric())  # Output: True

20. isprintable()

Returns True if all characters are printable (no control characters like \n or \t).

# Example 1
print("Hello World".isprintable())  # Output: True
# Example 2
print("Hello\nWorld".isprintable())  # Output: False

21. isspace()

Returns True if all characters are whitespace and there is at least one character.

# Example 1
print("   ".isspace())  # Output: True
# Example 2
print("  a  ".isspace())  # Output: False

22. istitle()

Returns True if the string is titlecased (each word starts with an uppercase letter, followed by lowercase).

# Example 1
print("Hello World".istitle())  # Output: True
# Example 2
print("Hello world".istitle())  # Output: False

23. isupper()

Returns True if all cased characters are uppercase and there is at least one cased character.

# Example 1
print("HELLO".isupper())  # Output: True
# Example 2
print("Hello".isupper())  # Output: False

24. join()

Joins an iterable of strings using the current string as a separator.

# Example 1
words = ["Python", "is", "awesome"]
print(" ".join(words))  # Output: "Python is awesome"
# Example 2
letters = ["a", "b", "c"]
print("-".join(letters))  # Output: "a-b-c"

25. ljust()

Left-justifies the string within a given width, padding on the right (default space).

# Example 1
s = "cat"
print(s.ljust(10, "."))  # Output: "cat......."
# Example 2
s = "id"
print(s.ljust(5) + "|")  # Output: "id   |"

26. lower()

Converts all characters in the string to lowercase.

# Example 1
s = "HELLO WORLD"
print(s.lower())  # Output: "hello world"
# Example 2
email = "User@EXAMPLE.com"
print(email.lower())  # Output: "user@example.com"

27. lstrip()

Removes leading whitespace (or specified characters) from the string.

# Example 1
s = "   hello"
print(s.lstrip())  # Output: "hello"
# Example 2
s = "xxxhello"
print(s.lstrip("x"))  # Output: "hello"

28. maketrans()

Creates a translation table to be used with translate(), mapping characters to replacements.

# Example 1
table = str.maketrans("abc", "xyz")
print("abcdef".translate(table))  # Output: "xyzdef"
# Example 2
table = str.maketrans("", "", "aeiou")  # delete vowels
print("hello world".translate(table))  # Output: "hll wrld"

29. partition()

Splits the string at the first occurrence of a separator, returning a 3-tuple: (before, separator, after).

# Example 1
s = "key=value"
print(s.partition("="))  # Output: ('key', '=', 'value')
# Example 2
s = "no-separator-here"
print(s.partition(":"))  # Output: ('no-separator-here', '', '')

30. removeprefix()

Removes a specified prefix from the string, if present (Python 3.9+).

# Example 1
s = "unhappy"
print(s.removeprefix("un"))  # Output: "happy"
# Example 2
url = "https://example.com"
print(url.removeprefix("https://"))  # Output: "example.com"

31. removesuffix()

Removes a specified suffix from the string, if present (Python 3.9+).

# Example 1
filename = "report.txt"
print(filename.removesuffix(".txt"))  # Output: "report"
# Example 2
s = "playing"
print(s.removesuffix("ing"))  # Output: "play"

32. replace()

Replaces all occurrences of a substring with another substring.

# Example 1
s = "I like cats"
print(s.replace("cats", "dogs"))  # Output: "I like dogs"
# Example 2
s = "aaaa"
print(s.replace("a", "b", 2))  # Output: "bbaa" (limit replacements to 2)

33. rfind()

Returns the highest index of a substring, or -1 if not found (searches from the right).

# Example 1
s = "hello world hello"
print(s.rfind("hello"))  # Output: 12
# Example 2
s = "abcabc"
print(s.rfind("z"))  # Output: -1

34. rindex()

Like rfind(), but raises ValueError if the substring is not found.

# Example 1
s = "hello world hello"
print(s.rindex("hello"))  # Output: 12
# Example 2
s = "abcabc"
try:
    print(s.rindex("z"))
except ValueError as e:
    print(f"Error: {e}")  # Output: Error: substring not found

35. rjust()

Right-justifies the string within a given width, padding on the left (default space).

# Example 1
s = "42"
print(s.rjust(5, "0"))  # Output: "00042"
# Example 2
s = "cat"
print(s.rjust(10) + "|")  # Output: "       cat|"

36. rpartition()

Splits the string at the last occurrence of a separator, returning a 3-tuple: (before, separator, after).

# Example 1
path = "/usr/local/bin"
print(path.rpartition("/"))  # Output: ('/usr/local', '/', 'bin')
# Example 2
s = "no-separator-here"
print(s.rpartition(":"))  # Output: ('', '', 'no-separator-here')

37. rsplit()

Splits the string from the right side, optionally limited by maxsplit.

# Example 1
s = "a,b,c,d"
print(s.rsplit(",", 1))  # Output: ['a,b,c', 'd']
# Example 2
path = "folder/subfolder/file.txt"
print(path.rsplit("/", 1))  # Output: ['folder/subfolder', 'file.txt']

38. rstrip()

Removes trailing whitespace (or specified characters) from the string.

# Example 1
s = "hello   "
print(s.rstrip())  # Output: "hello"
# Example 2
s = "hello***"
print(s.rstrip("*"))  # Output: "hello"

39. split()

Splits the string into a list using a separator (default: whitespace).

# Example 1
s = "the quick brown fox"
print(s.split())  # Output: ['the', 'quick', 'brown', 'fox']
# Example 2
csv_line = "name,age,city"
print(csv_line.split(","))  # Output: ['name', 'age', 'city']

40. splitlines()

Splits the string at line boundaries (\n, \r\n, etc.), returning a list of lines.

# Example 1
text = "line1\nline2\nline3"
print(text.splitlines())  # Output: ['line1', 'line2', 'line3']
# Example 2
text = "line1\nline2"
print(text.splitlines(keepends=True))  # Output: ['line1\n', 'line2']

41. startswith()

Checks whether the string starts with the specified prefix (or tuple of prefixes).

# Example 1
url = "https://example.com"
print(url.startswith("https"))  # Output: True
# Example 2
filename = "image.png"
print(filename.startswith(("img", "image", "photo")))  # Output: True

42. strip()

Removes leading and trailing whitespace (or specified characters) from the string.

# Example 1
s = "   hello world   "
print(s.strip())  # Output: "hello world"
# Example 2
s = "###title###"
print(s.strip("#"))  # Output: "title"

43. swapcase()

Swaps the case of all characters: uppercase becomes lowercase and vice versa.

# Example 1
s = "Hello World"
print(s.swapcase())  # Output: "hELLO wORLD"
# Example 2
s = "PyThOn"
print(s.swapcase())  # Output: "pYtHoN"

44. title()

Converts the string to title case (first letter of each word capitalized).

# Example 1
s = "the great gatsby"
print(s.title())  # Output: "The Great Gatsby"
# Example 2
s = "hello world! it's python"
print(s.title())  # Output: "Hello World! It'S Python"

45. translate()

Applies a translation table (created via maketrans()) to replace or delete characters.

# Example 1
table = str.maketrans("aeiou", "12345")
print("hello world".translate(table))  # Output: "h2ll4 w4rld"
# Example 2
table = str.maketrans({"a": None, "e": None})  # delete a and e
print("adventure".translate(table))  # Output: "dvntur"

46. upper()

Converts all characters in the string to uppercase.

# Example 1
s = "hello world"
print(s.upper())  # Output: "HELLO WORLD"
# Example 2
code = "abc123"
print(code.upper())  # Output: "ABC123"

47. zfill()

Pads the string on the left with zeros to fill a specified width (handles sign prefixes correctly).

# Example 1
s = "42"
print(s.zfill(5))  # Output: "00042"
# Example 2
s = "-42"
print(s.zfill(6))  # Output: "-00042"

Quick Reference Table

#MethodPurpose
1capitalize()Capitalize first letter
2casefold()Aggressive lowercase for matching
3center()Center-align with padding
4count()Count substring occurrences
5encode()Convert to bytes
6endswith()Check suffix
7expandtabs()Replace tabs with spaces
8find()Locate substring (returns -1 if missing)
9format()Template string formatting
10format_map()Format using a mapping
11index()Locate substring (raises error if missing)
12isalnum()Check alphanumeric
13isalpha()Check alphabetic
14isascii()Check ASCII-only
15isdecimal()Check decimal digits
16isdigit()Check digit characters
17isidentifier()Check valid identifier
18islower()Check lowercase
19isnumeric()Check numeric characters
20isprintable()Check printable characters
21isspace()Check whitespace
22istitle()Check title case
23isupper()Check uppercase
24join()Join iterable into string
25ljust()Left-justify with padding
26lower()Convert to lowercase
27lstrip()Strip leading characters
28maketrans()Build translation table
29partition()Split into 3 parts at first match
30removeprefix()Remove leading prefix
31removesuffix()Remove trailing suffix
32replace()Replace substring
33rfind()Locate substring from right
34rindex()Locate from right (raises error)
35rjust()Right-justify with padding
36rpartition()Split into 3 parts at last match
37rsplit()Split from the right
38rstrip()Strip trailing characters
39split()Split into list
40splitlines()Split at line boundaries
41startswith()Check prefix
42strip()Strip leading & trailing characters
43swapcase()Swap character case
44title()Convert to title case
45translate()Apply translation table
46upper()Convert to uppercase
47zfill()Zero-pad on the left