Python String Methods

Python provides a comprehensive set of string methods to perform various operations on strings. In this chapter, we will learn about all the Python String methods, along with examples and their respective outputs.

Table of Contents

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

1. capitalize()

Capitalizes the first character of the string.

s = "hello, world!"
print(s.capitalize())

Output:

Hello, world!

2. casefold()

Converts the string to lowercase, more aggressive than lower().

s = "HELLO, World!"
print(s.casefold())

Output:

hello, world!

3. center()

Centers the string within a specified width.

s = "hello"
print(s.center(20, '-'))

Output:

-------hello--------

4. count()

Counts the occurrences of a substring.

s = "hello, world! hello!"
print(s.count("hello"))

Output:

2

5. encode()

Encodes the string to a specified encoding.

s = "hello"
print(s.encode("utf-8"))

Output:

b'hello'

6. endswith()

Checks if the string ends with a specified suffix.

s = "hello, world!"
print(s.endswith("world!"))

Output:

True

7. expandtabs()

Expands tabs in the string to spaces.

s = "hello\tworld!"
print(s.expandtabs(4))

Output:

hello   world!

8. find()

Finds the first occurrence of a substring.

s = "hello, world!"
print(s.find("world"))

Output:

7

9. format()

Formats the string using placeholders.

s = "Hello, {}!"
print(s.format("world"))

Output:

Hello, world!

10. format_map()

Formats the string using a dictionary.

s = "Hello, {name}!"
print(s.format_map({'name': 'world'}))

Output:

Hello, world!

11. index()

Finds the first occurrence of a substring and raises an exception if not found.

s = "hello, world!"
print(s.index("world"))

Output:

7

12. isalnum()

Checks if all characters in the string are alphanumeric.

s = "hello123"
print(s.isalnum())

Output:

True

13. isalpha()

Checks if all characters in the string are alphabetic.

s = "hello"
print(s.isalpha())

Output:

True

14. isascii()

Checks if all characters in the string are ASCII.

s = "hello"
print(s.isascii())

Output:

True

15. isdecimal()

Checks if all characters in the string are decimal.

s = "12345"
print(s.isdecimal())

Output:

True

16. isdigit()

Checks if all characters in the string are digits.

s = "12345"
print(s.isdigit())

Output:

True

17. isidentifier()

Checks if the string is a valid identifier.

s = "hello_world"
print(s.isidentifier())

Output:

True

18. islower()

Checks if all characters in the string are lowercase.

s = "hello"
print(s.islower())

Output:

True

19. isnumeric()

Checks if all characters in the string are numeric.

s = "12345"
print(s.isnumeric())

Output:

True

20. isprintable()

Checks if all characters in the string are printable.

s = "hello world!"
print(s.isprintable())

Output:

True

21. isspace()

Checks if all characters in the string are whitespace.

s = "   "
print(s.isspace())

Output:

True

22. istitle()

Checks if the string is title-cased.

s = "Hello World"
print(s.istitle())

Output:

True

23. isupper()

Checks if all characters in the string are uppercase.

s = "HELLO"
print(s.isupper())

Output:

True

24. join()

Joins elements of an iterable with the string as the separator.

s = "-"
seq = ["a", "b", "c"]
print(s.join(seq))

Output:

a-b-c

25. ljust()

Left-justifies the string within a specified width.

s = "hello"
print(s.ljust(10, '-'))

Output:

hello-----

26. lower()

Converts the string to lowercase.

s = "HELLO"
print(s.lower())

Output:

hello

27. lstrip()

Removes leading characters.

s = "   hello"
print(s.lstrip())

Output:

hello

28. maketrans()

Creates a translation table for use with translate().

s = "hello"
trans = s.maketrans("hlo", "HL0")
print(s.translate(trans))

Output:

HeLLo

29. partition()

Splits the string at the first occurrence of the separator.

s = "hello, world"
print(s.partition(","))

Output:

('hello', ',', ' world')

30. replace()

Replaces occurrences of a substring with another substring.

s = "hello, world"
print(s.replace("world", "Python"))

Output:

hello, Python

31. rfind()

Finds the last occurrence of a substring.

s = "hello, hello, world"
print(s.rfind("hello"))

Output:

7

32. rindex()

Finds the last occurrence of a substring and raises an exception if not found.

s = "hello, hello, world"
print(s.rindex("hello"))

Output:

7

33. rjust()

Right-justifies the string within a specified width.

s = "hello"
print(s.rjust(10, '-'))

Output:

-----hello

34. rpartition()

Splits the string at the last occurrence of the separator.

s = "hello, world, hello"
print(s.rpartition(","))

Output:

('hello, world', ',', ' hello')

35. rsplit()

Splits the string from the right by the specified separator.

s = "hello, world, hello"
print(s.rsplit(","))

Output:

['hello', ' world', ' hello']

36. rstrip()

Removes trailing characters.



s = "hello   "
print(s.rstrip())

Output:

hello

37. split()

Splits the string by the specified separator.

s = "hello, world"
print(s.split(","))

Output:

['hello', ' world']

38. splitlines()

Splits the string at line breaks.

s = "hello\nworld"
print(s.splitlines())

Output:

['hello', 'world']

39. startswith()

Checks if the string starts with a specified prefix.

s = "hello, world"
print(s.startswith("hello"))

Output:

True

40. strip()

Removes leading and trailing characters.

s = "   hello   "
print(s.strip())

Output:

hello

41. swapcase()

Swaps the case of characters in the string.

s = "Hello, World!"
print(s.swapcase())

Output:

hELLO, wORLD!

42. title()

Converts the string to title case.

s = "hello world"
print(s.title())

Output:

Hello World

43. translate()

Translates the string using a translation table created by maketrans().

s = "hello"
trans = s.maketrans("hlo", "HL0")
print(s.translate(trans))

Output:

HeLLo

44. upper()

Converts the string to uppercase.

s = "hello"
print(s.upper())

Output:

HELLO

45. zfill()

Pads the string on the left with zeros to fill a specified width.

s = "42"
print(s.zfill(5))

Output:

00042

Conclusion

We can use Python’s string methods to manipulate and work with strings. By understanding and utilizing these methods, you can handle a wide range of string operations efficiently. Whether you need to modify the case, split or join strings, search for substrings, or format strings, these built-in methods make it easy to perform these tasks.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top