Python String Methods

Python provides a rich set of string methods for manipulating and processing string data. These methods can perform tasks such as searching, modifying, formatting, and analyzing strings. Here’s a comprehensive overview of the most commonly used Python string methods:

1. Case-Related Methods

  • lower(): Converts all characters in a string to lowercase.
    "HELLO".lower()  # Output: "hello"
    
  • upper(): Converts all characters in a string to uppercase.
    "hello".upper()  # Output: "HELLO"
    
  • capitalize(): Converts the first character of the string to uppercase and the rest to lowercase.
    "hello world".capitalize()  # Output: "Hello world"
    
  • title(): Converts the first letter of each word to uppercase.
    "hello world".title()  # Output: "Hello World"
    
  • swapcase(): Swaps the case of all characters in the string (uppercase becomes lowercase and vice versa).
    "Hello World".swapcase()  # Output: "hELLO wORLD"
    

2. Searching and Checking Methods

  • find(substring): Returns the lowest index where the substring is found in the string, or -1 if not found.
    "hello world".find("world")  # Output: 6
    
  • rfind(substring): Returns the highest index where the substring is found, or -1 if not found.
    "hello world".rfind("l")  # Output: 9
    
  • index(substring): Like find(), but raises a ValueError if the substring is not found.
    "hello world".index("world")  # Output: 6
    
  • rindex(substring): Like rfind(), but raises a ValueError if the substring is not found.
    "hello world".rindex("l")  # Output: 9
    
  • startswith(prefix): Returns True if the string starts with the specified prefix.
    "hello world".startswith("hello")  # Output: True
    
  • endswith(suffix): Returns True if the string ends with the specified suffix.
    "hello world".endswith("world")  # Output: True
    
  • count(substring): Returns the number of occurrences of the substring in the string.
    "hello world".count("l")  # Output: 3
    
  • isalnum(): Returns True if all characters in the string are alphanumeric (letters or digits) and there is at least one character.
    "hello123".isalnum()  # Output: True
    
  • isalpha(): Returns True if all characters in the string are alphabetic and there is at least one character.
    "hello".isalpha()  # Output: True
    
  • isdigit(): Returns True if all characters in the string are digits.
    "12345".isdigit()  # Output: True
    
  • isspace(): Returns True if all characters in the string are whitespace characters.
    "   ".isspace()  # Output: True
    
  • isupper(): Returns True if all characters in the string are uppercase and there is at least one alphabetic character.
    "HELLO".isupper()  # Output: True
    
  • islower(): Returns True if all characters in the string are lowercase and there is at least one alphabetic character.
    "hello".islower()  # Output: True
    

3. Modifying and Manipulating Strings

  • replace(old, new): Replaces all occurrences of the substring old with new.
    "hello world".replace("world", "Python")  # Output: "hello Python"
    
  • strip(): Removes leading and trailing whitespace (or specified characters) from the string.
    "  hello  ".strip()  # Output: "hello"
    
  • lstrip(): Removes leading whitespace (or specified characters) from the string.
    "  hello".lstrip()  # Output: "hello"
    
  • rstrip(): Removes trailing whitespace (or specified characters) from the string.
    "hello  ".rstrip()  # Output: "hello"
    
  • join(iterable): Joins the elements of an iterable (like a list) into a single string, using the string as a separator.
    ", ".join(["apple", "banana", "cherry"])  # Output: "apple, banana, cherry"
    
  • split(separator): Splits the string into a list of substrings using the specified separator.
    "hello world".split()  # Output: ["hello", "world"]
    
  • rsplit(separator): Splits the string from the right side.
    "apple,banana,cherry".rsplit(",", 1)  # Output: ['apple,banana', 'cherry']
    
  • partition(separator): Splits the string into a tuple of three parts: the part before the separator, the separator itself, and the part after it.
    "hello world".partition(" ")  # Output: ("hello", " ", "world")
    
  • rpartition(separator): Like partition(), but splits from the right.
    "hello world".rpartition(" ")  # Output: ("hello", " ", "world")
    
  • splitlines(): Splits the string at line breaks and returns a list of lines.
    "hello\nworld".splitlines()  # Output: ["hello", "world"]
    

4. String Formatting Methods

  • format(*args, **kwargs): Formats the string by inserting values into placeholders {}.
    "Hello, {}!".format("Alice")  # Output: "Hello, Alice!"
    
  • format_map(mapping): Similar to format(), but uses a dictionary for formatting.
    "Hello, {name}!".format_map({"name": "Alice"})  # Output: "Hello, Alice!"
    
  • zfill(width): Pads the string on the left with zeros until the total string length equals the specified width.
    "42".zfill(5)  # Output: "00042"
    

5. Character-Related Methods

  • ord(c): Returns the Unicode code point of the given character.
    ord('a')  # Output: 97
    
  • chr(i): Returns the string representing a character whose Unicode code point is the integer i.
    chr(97)  # Output: 'a'
    

6. Aligning and Justifying Strings

  • center(width): Centers the string within the specified width, padding with spaces.
    "hello".center(10)  # Output: "  hello   "
    
  • ljust(width): Left-aligns the string within the specified width, padding with spaces.
    "hello".ljust(10)  # Output: "hello     "
    
  • rjust(width): Right-aligns the string within the specified width, padding with spaces.
    "hello".rjust(10)  # Output: "     hello"
    

Summary:

  • Python provides various string methods for searching, manipulating, formatting, and checking strings.
  • Modifying methods like replace(), strip(), join(), and split() are commonly used for transforming strings.
  • Checking methods like isalnum(), isalpha(), isdigit(), and startswith() are useful for validating strings.
  • Formatting methods like format() and zfill() allow for dynamic string creation.
Leave a Reply 0

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