Python string methods

Python string methods

1. capitalize()

  • Converts the first character of the string to uppercase.
  • Example: 'hello'.capitalize() → 'Hello'


2. casefold()

  • Converts the string to lowercase, more aggressive than lower().
  • Example: 'HELLO'.casefold() → 'hello'


3. center(width, [fillchar])

  • Centers the string within the specified width and fills the rest with the optional fill character.
  • Example: 'hello'.center(10, '-') → '--hello---'


4. count(substring, [start, end])

  • Counts occurrences of the substring within the string.
  • Example: 'hello world'.count('o') → 2


5. encode(encoding, [errors])

  • Encodes the string into the specified encoding.
  • Example: 'hello'.encode('utf-8') → b'hello'


6. endswith(suffix, [start, end])

  • Returns True if the string ends with the specified suffix.
  • Example: 'hello'.endswith('lo') → True


7. expandtabs(tabsize)

  • Expands tabs in a string to multiple spaces.
  • Example: 'hello\tworld'.expandtabs(4) → 'hello world'


8. find(substring, [start, end])

  • Returns the lowest index of the substring if found, else -1.
  • Example: 'hello'.find('l') → 2


9. format(*args, **kwargs)

  • Formats the string with the specified arguments.
  • Example: 'Hello, {}'.format('world') → 'Hello, world'


10. format_map(mapping)

  • Formats the string using a dictionary mapping.
  • Example: '{name} is {age}'.format_map({'name': 'Alice', 'age': 30}) → 'Alice is 30'


11. index(substring, [start, end])

  • Like find(), but raises ValueError if the substring is not found.
  • Example: 'hello'.index('l') → 2


12. isalnum()

  • Returns True if the string is alphanumeric (contains only letters and numbers).
  • Example: 'hello123'.isalnum() → True


13. isalpha()

  • Returns True if the string contains only letters.
  • Example: 'hello'.isalpha() → True


14. isascii()

  • Returns True if all characters in the string are ASCII.
  • Example: 'hello'.isascii() → True


15. isdecimal()

  • Returns True if the string contains only decimal characters.
  • Example: '123'.isdecimal() → True


16. isdigit()

  • Returns True if the string contains only digits.
  • Example: '123'.isdigit() → True


17. isidentifier()

  • Returns True if the string is a valid Python identifier.
  • Example: 'hello'.isidentifier() → True


18. islower()

  • Returns True if all characters in the string are lowercase.
  • Example: 'hello'.islower() → True


19. isnumeric()

  • Returns True if the string contains only numeric characters.
  • Example: '123'.isnumeric() → True


20. isprintable()

  • Returns True if all characters are printable.
  • Example: 'hello\n'.isprintable() → False


21. isspace()

  • Returns True if the string contains only whitespace.
  • Example: ' '.isspace() → True


22. istitle()

  • Returns True if the string follows title case.
  • Example: 'Hello World'.istitle() → True


23. isupper()

  • Returns True if all characters are uppercase.
  • Example: 'HELLO'.isupper() → True


24. join(iterable)

  • Joins elements of an iterable with the string as a separator.
  • Example: '-'.join(['hello', 'world']) → 'hello-world'


25. ljust(width, [fillchar])

  • Left-justifies the string within the given width and fills the rest with the optional fill character.
  • Example: 'hello'.ljust(10, '-') → 'hello-----'


26. lower()

  • Converts all characters to lowercase.
  • Example: 'HELLO'.lower() → 'hello'


27. lstrip([chars])

  • Removes leading whitespace (or specified characters).
  • Example: ' hello'.lstrip() → 'hello'


28. maketrans(x[, y[, z]])

  • Returns a translation table usable by translate().
  • Example: str.maketrans('a', 'b')


29. partition(sep)


  • Splits the string into three parts: before the separator, the separator, and after the separator.
  • Example: 'hello world'.partition(' ') → ('hello', ' ', 'world')


30. replace(old, new[, count])

  • Replaces occurrences of a substring with another.
  • Example: 'hello'.replace('l', 'x') → 'hexxo'


31. rfind(substring, [start, end])

  • Returns the highest index of the substring if found, else -1.
  • Example: 'hello'.rfind('l') → 3


32. rindex(substring, [start, end])

  • Like rfind(), but raises ValueError if the substring is not found.
  • Example: 'hello'.rindex('l') → 3


33. rjust(width, [fillchar])

  • Right-justifies the string and fills the rest with the optional fill character.
  • Example: 'hello'.rjust(10, '-') → '-----hello'


34. rpartition(sep)

  • Like partition(), but splits into three parts using the last occurrence of the separator.
  • Example: 'hello world'.rpartition(' ') → ('hello', ' ', 'world')


35. rsplit([sep[, maxsplit]])

  • Splits the string from the right by the separator.
  • Example: 'a,b,c'.rsplit(',', 1) → ['a,b', 'c']


36. rstrip([chars])

  • Removes trailing whitespace (or specified characters).
  • Example: 'hello '.rstrip() → 'hello'


37. split([sep[, maxsplit]])

  • Splits the string at each separator.
  • Example: 'a,b,c'.split(',') → ['a', 'b', 'c']


38. splitlines([keepends])

  • Splits the string at line breaks.
  • Example: 'hello\nworld'.splitlines() → ['hello', 'world']


39. startswith(prefix, [start, end])

  • Returns True if the string starts with the specified prefix.
  • Example: 'hello'.startswith('he') → True


40. strip([chars])

  • Removes leading and trailing whitespace (or specified characters).
  • Example: ' hello '.strip() → 'hello'


41. swapcase()

  • Swaps the case of all characters.
  • Example: 'Hello'.swapcase() → 'hELLO'


42. title()

  • Converts the first letter of each word to uppercase.
  • Example: 'hello world'.title() → 'Hello World'


43. translate(table)

  • Translates the string using a translation table.
  • Example: 'abc'.translate(str.maketrans('a', 'b')) → 'bbc'


44. upper()

  • Converts all characters to uppercase.
  • Example: 'hello'.upper() → 'HELLO'


45. zfill(width)

  • Pads the string with leading zeros until it reaches the specified width.
  • Example: '42'.zfill(5) → '00042'

要查看或添加评论,请登录

Naresh Maddela的更多文章

社区洞察

其他会员也浏览了