DEV Community

Usool
Usool

Posted on

A Quick Guide to Python String Methods with Examples

Introduction

Python strings come with numerous built-in methods to manipulate text efficiently. Below is a quick guide to all the key string methods with brief explanations and examples.

1. capitalize()

Converts the first character to uppercase.

"text".capitalize()  # 'Text'
Enter fullscreen mode Exit fullscreen mode

2. casefold()

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

"TeXt".casefold()  # 'text'
Enter fullscreen mode Exit fullscreen mode

3. center(width, fillchar)

Centers the string with specified width and optional fill character.

"text".center(10, '-')  # '--text---'
Enter fullscreen mode Exit fullscreen mode

4. count(substring, start, end)

Counts occurrences of a substring in the string.

"hello".count('l')  # 2
Enter fullscreen mode Exit fullscreen mode

5. encode(encoding, errors)

Encodes the string using the specified encoding.

"text".encode('utf-8')  # b'text'
Enter fullscreen mode Exit fullscreen mode

6. endswith(suffix, start, end)

Checks if the string ends with the specified suffix.

"text".endswith('xt')  # True
Enter fullscreen mode Exit fullscreen mode

7. expandtabs(tabsize)

Replaces tabs with spaces.

"1\t2\t3".expandtabs(4)  # '1   2   3'
Enter fullscreen mode Exit fullscreen mode

8. find(substring, start, end)

Finds the index of the first occurrence of a substring.

"hello".find('e')  # 1
Enter fullscreen mode Exit fullscreen mode

9. format(*args, **kwargs)

Formats a string with placeholders.

"Hello, {}".format("world")  # 'Hello, world'
Enter fullscreen mode Exit fullscreen mode

10. format_map(mapping)

Formats a string using a dictionary.

"{name}".format_map({"name": "John"})  # 'John'
Enter fullscreen mode Exit fullscreen mode

11. index(substring, start, end)

Finds the index of the first occurrence (raises error if not found).

"hello".index('l')  # 2
Enter fullscreen mode Exit fullscreen mode

12. isalnum()

Checks if all characters are alphanumeric.

"text123".isalnum()  # True
Enter fullscreen mode Exit fullscreen mode

13. isalpha()

Checks if all characters are alphabetic.

"text".isalpha()  # True
Enter fullscreen mode Exit fullscreen mode

14. isdecimal()

Checks if all characters are decimal digits.

"123".isdecimal()  # True
Enter fullscreen mode Exit fullscreen mode

15. isdigit()

Checks if all characters are digits.

"123".isdigit()  # True
Enter fullscreen mode Exit fullscreen mode

16. islower()

Checks if all characters are lowercase.

"text".islower()  # True
Enter fullscreen mode Exit fullscreen mode

17. isnumeric()

Checks if all characters are numeric.

"123".isnumeric()  # True
Enter fullscreen mode Exit fullscreen mode

18. isspace()

Checks if all characters are whitespace.

"   ".isspace()  # True
Enter fullscreen mode Exit fullscreen mode

19. istitle()

Checks if the string is title-cased.

"Hello World".istitle()  # True
Enter fullscreen mode Exit fullscreen mode

20. isupper()

Checks if all characters are uppercase.

"TEXT".isupper()  # True
Enter fullscreen mode Exit fullscreen mode

21. join(iterable)

Joins elements of an iterable with a string separator.

",".join(["a", "b", "c"])  # 'a,b,c'
Enter fullscreen mode Exit fullscreen mode

22. ljust(width, fillchar)

Left-aligns the string with specified width.

"text".ljust(10, '-')  # 'text------'
Enter fullscreen mode Exit fullscreen mode

23. lower()

Converts all characters to lowercase.

"TEXT".lower()  # 'text'
Enter fullscreen mode Exit fullscreen mode

24. lstrip(chars)

Removes leading characters.

"   text".lstrip()  # 'text'
Enter fullscreen mode Exit fullscreen mode

25. maketrans(x, y, z)

Creates a translation table for translate().

str.maketrans("abc", "123")  # mapping table
Enter fullscreen mode Exit fullscreen mode

26. partition(separator)

Splits the string at the first occurrence of separator.

"text_partition".partition('_')  # ('text', '_', 'partition')
Enter fullscreen mode Exit fullscreen mode

27. replace(old, new, count)

Replaces occurrences of a substring.

"hello".replace("l", "x")  # 'hexxo'
Enter fullscreen mode Exit fullscreen mode

28. rfind(substring, start, end)

Finds the last occurrence of a substring.

"hello".rfind('l')  # 3
Enter fullscreen mode Exit fullscreen mode

29. rindex(substring, start, end)

Finds the last occurrence (raises error if not found).

"hello".rindex('l')  # 3
Enter fullscreen mode Exit fullscreen mode

30. rjust(width, fillchar)

Right-aligns the string with specified width.

"text".rjust(10, '-')  # '------text'
Enter fullscreen mode Exit fullscreen mode

31. rpartition(separator)

Splits the string at the last occurrence of the separator.

"text_rpartition".rpartition('_')  # ('text', '_', 'rpartition')
Enter fullscreen mode Exit fullscreen mode

32. rsplit(separator, maxsplit)

Splits the string from the right.

"1,2,3".rsplit(',', 1)  # ['1,2', '3']
Enter fullscreen mode Exit fullscreen mode

33. rstrip(chars)

Removes trailing characters.

"text   ".rstrip()  # 'text'
Enter fullscreen mode Exit fullscreen mode

34. split(separator, maxsplit)

Splits a string into a list.

"1,2,3".split(',')  # ['1', '2', '3']
Enter fullscreen mode Exit fullscreen mode

35. splitlines(keepends)

Splits by line breaks.

"hello\nworld".splitlines()  # ['hello', 'world']
Enter fullscreen mode Exit fullscreen mode

36. startswith(prefix, start, end)

Checks if the string starts with the specified prefix.

"text".startswith('t')  # True
Enter fullscreen mode Exit fullscreen mode

37. strip(chars)

Removes leading and trailing characters.

"   text   ".strip()  # 'text'
Enter fullscreen mode Exit fullscreen mode

38. swapcase()

Swaps the case of all characters.

"Hello".swapcase()  # 'hELLO'
Enter fullscreen mode Exit fullscreen mode

39. title()

Converts the string to title case.

"hello world".title()  # 'Hello World'
Enter fullscreen mode Exit fullscreen mode

40. translate(table)

Translates the string using a translation table.

"text".translate(str.maketrans("t", "T"))  # 'TexT'
Enter fullscreen mode Exit fullscreen mode

41. upper()

Converts all characters to uppercase.

"text".upper()  # 'TEXT'
Enter fullscreen mode Exit fullscreen mode

42. zfill(width)

Pads the string with zeros on the left.

"42".zfill(5)  # '00042'
Enter fullscreen mode Exit fullscreen mode

Conclusion

Python’s string methods allow for efficient and readable text manipulation. Whether you're formatting, splitting, or modifying text, these methods cover nearly every scenario you’ll encounter in string processing.

Top comments (0)