Thursday, January 23, 2025
HomeProgrammingPython String Methods

Python String Methods

Python provides a wide variety of string methods to perform different operations. Here’s a list of some commonly used string methods in Python:

1. capitalize()

  • Capitalizes the first letter of the string and makes all other letters lowercase.
text = "hello"
print(text.capitalize())  # Output: "Hello"

2. casefold()

  • Converts the string to lowercase, useful for case-insensitive comparisons.
text = "HELLO"
print(text.casefold())  # Output: "hello"

3. center(width, fillchar=' ')

  • Centers the string within a given width.
text = "hello"
print(text.center(10, "*"))  # Output: "**hello***"

4. count(substring, start=0, end=len(string))

  • Returns the number of times a substring appears in the string.
text = "hello world"
print(text.count("o"))  # Output: 2

5. encode(encoding='utf-8')

  • Returns an encoded version of the string as bytes.
text = "hello"
print(text.encode())  # Output: b'hello'

6. endswith(suffix, start=0, end=len(string))

  • Checks if the string ends with the specified suffix.
text = "hello"
print(text.endswith("lo"))  # Output: True

7. expandtabs(tabsize=8)

  • Expands tabs in the string to the specified number of spaces.
text = "hello\tworld"
print(text.expandtabs(4))  # Output: "hello   world"

8. find(substring, start=0, end=len(string))

  • Returns the lowest index at which the substring is found, or -1 if not found.
text = "hello world"
print(text.find("world"))  # Output: 6

9. format(*args, **kwargs)

  • Used for formatting strings by placing values inside the string using curly braces.
text = "Hello, {}!"
print(text.format("world"))  # Output: "Hello, world!"

10. index(substring, start=0, end=len(string))

  • Similar to find(), but raises a ValueError if the substring is not found.
text = "hello world"
print(text.index("world"))  # Output: 6

11. isalnum()

  • Returns True if all characters in the string are alphanumeric (letters and digits), otherwise False.
text = "hello123"
print(text.isalnum())  # Output: True

12. isalpha()

  • Returns True if all characters in the string are alphabetic (letters only).
text = "hello"
print(text.isalpha())  # Output: True

13. isdigit()

  • Returns True if all characters in the string are digits.
text = "12345"
print(text.isdigit())  # Output: True

14. join(iterable)

  • Concatenates the elements of an iterable (like a list or tuple) into a single string, using the string as a separator.
text = "-"
print(text.join(["apple", "banana", "cherry"]))  # Output: "apple-banana-cherry"

15. lower()

  • Converts all characters in the string to lowercase.
text = "HELLO"
print(text.lower())  # Output: "hello"

16. lstrip(chars=None)

  • Removes leading (left) whitespace or a specified set of characters.
text = "  hello"
print(text.lstrip())  # Output: "hello"

17. replace(old, new, count=-1)

  • Replaces occurrences of a substring with a new substring.
text = "hello world"
print(text.replace("world", "Python"))  # Output: "hello Python"

18. split(separator=None, maxsplit=-1)

  • Splits the string into a list of substrings based on the separator.
text = "apple,banana,cherry"
print(text.split(","))  # Output: ['apple', 'banana', 'cherry']

19. startswith(prefix, start=0, end=len(string))

  • Checks if the string starts with the specified prefix.
text = "hello"
print(text.startswith("he"))  # Output: True

20. strip(chars=None)

  • Removes leading and trailing whitespace or a specified set of characters.
text = "  hello  "
print(text.strip())  # Output: "hello"

21. swapcase()

  • Swaps the case of all characters in the string (uppercase becomes lowercase and vice versa).
text = "Hello"
print(text.swapcase())  # Output: "hELLO"

22. title()

  • Converts the first character of each word to uppercase and the rest to lowercase.
text = "hello world"
print(text.title())  # Output: "Hello World"

23. upper()

  • Converts all characters in the string to uppercase.
text = "hello"
print(text.upper())  # Output: "HELLO"

24. zfill(width)

  • Pads the string with zeros on the left until the string reaches the specified width.
text = "42"
print(text.zfill(5))  # Output: "00042"

This is just a small selection of Python string methods. If you want to explore more or need an example of a specific method, feel free to ask!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x