Skip to main content

Common String Methods

Strings are one of the most commonly used data types in Python. This page doesn't aim to list every method -- it keeps only the ones I look back at most often.

Case Conversion

text = "Hello World"

print(text.lower())
print(text.upper())
print(text.title())

Stripping Whitespace

text = "  hello  "

print(text.strip())
print(text.lstrip())
print(text.rstrip())

Searching and Checking

text = "hello world"

print(text.find("world")) # returns -1 if not found
print(text.startswith("hello"))
print(text.endswith("world"))
print("world" in text)

Replacing

text = "2024-04-01"
print(text.replace("-", "/"))

Splitting and Joining

text = "alice,bob,charlie"
parts = text.split(",")

print(parts)
print("-".join(parts))

Character Type Checking

print("123".isdigit())
print("abc".isalpha())
print("abc123".isalnum())
print(" ".isspace())
name = "alice"
score = 95

print(f"{name}: {score}")
print("{:>8}".format(name))
print("3.14159 -> {:.2f}".format(3.14159))

Points I tend to forget

  • find() returns -1 when not found, instead of raising an error.
  • split() splits on any whitespace by default.
  • join() is a method on the separator string, not on the list.
  • Strings are immutable objects; methods return new strings and don't modify the original in place.