Skip to main content

Python String Methods

Python provides a rich set of methods for string manipulation. This guide covers the most commonly used string methods, their syntax, and practical examples.

Case Modification

  1. upper(): Converts all characters to uppercase

    "hello".upper()  # "HELLO"
  2. lower(): Converts all characters to lowercase

    "WORLD".lower()  # "world"
  3. capitalize(): Capitalizes the first character

    "python".capitalize()  # "Python"
  4. title(): Converts the first character of each word to uppercase

    "hello world".title()  # "Hello World"
  5. swapcase(): Swaps case for all characters

    "PyThOn".swapcase()  # "pYtHoN"

Searching and Replacing

  1. find(sub[, start[, end]]): Returns the lowest index of substring

    "Hello".find("l")  # 2
  2. rfind(sub[, start[, end]]): Returns the highest index of substring

    "Hello".rfind("l")  # 3
  3. index(sub[, start[, end]]): Like find(), but raises ValueError when not found

    "Hello".index("o")  # 4
  4. rindex(sub[, start[, end]]): Like rfind(), but raises ValueError when not found

    "Hello".rindex("l")  # 3
  5. replace(old, new[, count]): Replaces occurrences of a substring

    "Hello".replace("l", "L")  # "HeLLo"

Checking String Content

  1. startswith(prefix[, start[, end]]): Checks if string starts with the specified prefix

    "Python".startswith("Py")  # True
  2. endswith(suffix[, start[, end]]): Checks if string ends with the specified suffix

    "Python".endswith("on")  # True
  3. isalpha(): Checks if all characters are alphabetic

    "Python".isalpha()  # True
    "Python3".isalpha() # False
  4. isalnum(): Checks if all characters are alphanumeric

    "Python3".isalnum()  # True
  5. isdigit(): Checks if all characters are digits

    "123".isdigit()  # True
  6. isspace(): Checks if all characters are whitespace

    "   ".isspace()  # True

Stripping and Splitting

  1. strip([chars]): Removes leading and trailing characters (default: whitespace)

    "  Python  ".strip()  # "Python"
  2. lstrip([chars]): Removes leading characters (default: whitespace)

    "  Python".lstrip()  # "Python"
  3. rstrip([chars]): Removes trailing characters (default: whitespace)

    "Python  ".rstrip()  # "Python"
  4. split([sep[, maxsplit]]): Splits the string into a list

    "Hello,World".split(",")  # ["Hello", "World"]
  5. rsplit([sep[, maxsplit]]): Splits the string from the right

    "a,b,c,d".rsplit(",", 2)  # ['a,b', 'c', 'd']
  6. splitlines([keepends]): Splits the string at line breaks

    "Hello\nWorld".splitlines()  # ["Hello", "World"]

Joining and Formatting

  1. join(iterable): Joins elements of an iterable using the string as separator

    ",".join(["a", "b", "c"])  # "a,b,c"
  2. format(*args, **kwargs): Formats the string

    "{} {}".format("Hello", "World")  # "Hello World"
  3. center(width[, fillchar]): Centers string within width

    "Python".center(10, "-")  # "--Python--"
  4. ljust(width[, fillchar]): Left-justifies string within width

    "Python".ljust(10, "-")  # "Python----"
  5. rjust(width[, fillchar]): Right-justifies string within width

    "Python".rjust(10, "-")  # "----Python"
  6. zfill(width): Pads string on the left with zeros

    "42".zfill(5)  # "00042"

Encoding and Decoding

  1. encode([encoding[, errors]]): Returns encoded version of the string

    "Pythön".encode("utf-8")  # b'Pyth\xc3\xb6n'
  2. decode([encoding[, errors]]): Decodes the string using the codec registered for encoding

    b'Pyth\xc3\xb6n'.decode("utf-8")  # "Pythön"

Miscellaneous

  1. count(sub[, start[, end]]): Counts non-overlapping occurrences of substring

    "Mississippi".count("ss")  # 2
  2. expandtabs([tabsize]): Expands tabs in string to spaces

    "a\tb\tc".expandtabs(4)  # "a   b   c"
  3. maketrans(x[, y[, z]]): Returns a translation table usable for translate()

    trans = str.maketrans("aeiou", "12345")
    "hello".translate(trans) # "h2ll4"

These string methods provide powerful tools for string manipulation in Python. Understanding and effectively using these methods can significantly enhance your text processing capabilities.