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'
2. casefold()
Converts string to lowercase (more aggressive than lower()
).
"TeXt".casefold() # 'text'
3. center(width, fillchar)
Centers the string with specified width and optional fill character.
"text".center(10, '-') # '--text---'
4. count(substring, start, end)
Counts occurrences of a substring in the string.
"hello".count('l') # 2
5. encode(encoding, errors)
Encodes the string using the specified encoding.
"text".encode('utf-8') # b'text'
6. endswith(suffix, start, end)
Checks if the string ends with the specified suffix.
"text".endswith('xt') # True
7. expandtabs(tabsize)
Replaces tabs with spaces.
"1\t2\t3".expandtabs(4) # '1 2 3'
8. find(substring, start, end)
Finds the index of the first occurrence of a substring.
"hello".find('e') # 1
9. format(*args, **kwargs)
Formats a string with placeholders.
"Hello, {}".format("world") # 'Hello, world'
10. format_map(mapping)
Formats a string using a dictionary.
"{name}".format_map({"name": "John"}) # 'John'
11. index(substring, start, end)
Finds the index of the first occurrence (raises error if not found).
"hello".index('l') # 2
12. isalnum()
Checks if all characters are alphanumeric.
"text123".isalnum() # True
13. isalpha()
Checks if all characters are alphabetic.
"text".isalpha() # True
14. isdecimal()
Checks if all characters are decimal digits.
"123".isdecimal() # True
15. isdigit()
Checks if all characters are digits.
"123".isdigit() # True
16. islower()
Checks if all characters are lowercase.
"text".islower() # True
17. isnumeric()
Checks if all characters are numeric.
"123".isnumeric() # True
18. isspace()
Checks if all characters are whitespace.
" ".isspace() # True
19. istitle()
Checks if the string is title-cased.
"Hello World".istitle() # True
20. isupper()
Checks if all characters are uppercase.
"TEXT".isupper() # True
21. join(iterable)
Joins elements of an iterable with a string separator.
",".join(["a", "b", "c"]) # 'a,b,c'
22. ljust(width, fillchar)
Left-aligns the string with specified width.
"text".ljust(10, '-') # 'text------'
23. lower()
Converts all characters to lowercase.
"TEXT".lower() # 'text'
24. lstrip(chars)
Removes leading characters.
" text".lstrip() # 'text'
25. maketrans(x, y, z)
Creates a translation table for translate()
.
str.maketrans("abc", "123") # mapping table
26. partition(separator)
Splits the string at the first occurrence of separator.
"text_partition".partition('_') # ('text', '_', 'partition')
27. replace(old, new, count)
Replaces occurrences of a substring.
"hello".replace("l", "x") # 'hexxo'
28. rfind(substring, start, end)
Finds the last occurrence of a substring.
"hello".rfind('l') # 3
29. rindex(substring, start, end)
Finds the last occurrence (raises error if not found).
"hello".rindex('l') # 3
30. rjust(width, fillchar)
Right-aligns the string with specified width.
"text".rjust(10, '-') # '------text'
31. rpartition(separator)
Splits the string at the last occurrence of the separator.
"text_rpartition".rpartition('_') # ('text', '_', 'rpartition')
32. rsplit(separator, maxsplit)
Splits the string from the right.
"1,2,3".rsplit(',', 1) # ['1,2', '3']
33. rstrip(chars)
Removes trailing characters.
"text ".rstrip() # 'text'
34. split(separator, maxsplit)
Splits a string into a list.
"1,2,3".split(',') # ['1', '2', '3']
35. splitlines(keepends)
Splits by line breaks.
"hello\nworld".splitlines() # ['hello', 'world']
36. startswith(prefix, start, end)
Checks if the string starts with the specified prefix.
"text".startswith('t') # True
37. strip(chars)
Removes leading and trailing characters.
" text ".strip() # 'text'
38. swapcase()
Swaps the case of all characters.
"Hello".swapcase() # 'hELLO'
39. title()
Converts the string to title case.
"hello world".title() # 'Hello World'
40. translate(table)
Translates the string using a translation table.
"text".translate(str.maketrans("t", "T")) # 'TexT'
41. upper()
Converts all characters to uppercase.
"text".upper() # 'TEXT'
42. zfill(width)
Pads the string with zeros on the left.
"42".zfill(5) # '00042'
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)