Python Basics — String Methods

3 minute read

String Methods

Python strings come with dozens of built-in methods. Here are the most useful ones, organized by category.

Case Methods

text = "hello, World!"

print(text.upper())       # HELLO, WORLD!
print(text.lower())       # hello, world!
print(text.title())       # Hello, World!
print(text.capitalize())  # Hello, world!
print(text.swapcase())    # HELLO, wORLD!

casefold() — Aggressive Lowering

german = "Straße"
print(german.lower())     # straße
print(german.casefold())  # strasse  (better for comparisons)

Search Methods

find() and index()

text = "Hello, World!"

# find() returns -1 if not found
print(text.find("World"))     # 7
print(text.find("Python"))    # -1

# index() raises ValueError if not found
print(text.index("World"))    # 7
# print(text.index("Python"))  # ValueError

rfind() and rindex() — Search from Right

path = "/home/user/docs/file.txt"
print(path.rfind("/"))   # 15 (last occurrence)

count()

text = "banana"
print(text.count("a"))   # 3
print(text.count("na"))  # 2

startswith() and endswith()

filename = "report.pdf"

print(filename.startswith("report"))  # True
print(filename.endswith(".pdf"))      # True
print(filename.endswith((".pdf", ".doc", ".txt")))  # True (tuple of suffixes)

Modification Methods

Since strings are immutable, these all return new strings.

replace()

text = "Hello, World!"
print(text.replace("World", "Python"))  # Hello, Python!
print(text.replace("l", "L"))          # HeLLo, WorLd!
print(text.replace("l", "L", 1))       # HeLlo, World! (max 1 replacement)

strip(), lstrip(), rstrip()

Remove whitespace (or specified characters) from the edges:

text = "   Hello, World!   "

print(text.strip())     # "Hello, World!"
print(text.lstrip())    # "Hello, World!   "
print(text.rstrip())    # "   Hello, World!"
url = "https://example.com///"
print(url.rstrip("/"))  # https://example.com

split()

Split a string into a list:

text = "apple banana cherry"
print(text.split())          # ['apple', 'banana', 'cherry']

csv_line = "Alice,25,NYC"
print(csv_line.split(","))   # ['Alice', '25', 'NYC']

# Limit splits
text = "one-two-three-four"
print(text.split("-", 2))    # ['one', 'two', 'three-four']

splitlines()

text = "Line 1\nLine 2\nLine 3"
print(text.splitlines())    # ['Line 1', 'Line 2', 'Line 3']

join()

Join a list into a string:

words = ["Hello", "World"]
print(" ".join(words))      # Hello World
print(", ".join(words))     # Hello, World
print("-".join(words))      # Hello-World
# Common pattern: join with newlines
lines = ["Line 1", "Line 2", "Line 3"]
print("\n".join(lines))

Validation Methods

These return True or False:

print("123".isdigit())      # True
print("abc".isalpha())      # True
print("abc123".isalnum())   # True
print("   ".isspace())      # True
print("Hello".istitle())    # True
print("hello".islower())    # True
print("HELLO".isupper())    # True

Practical: Input Validation

username = input("Enter username (letters and digits only): ")

if username.isalnum():
    print(f"Valid username: {username}")
else:
    print("Invalid! Only letters and digits allowed.")

Alignment Methods

text = "Hello"

print(text.center(20))       #        Hello
print(text.center(20, "-"))  # -------Hello--------
print(text.ljust(20, "."))   # Hello...............
print(text.rjust(20, "."))   # ...............Hello
print(text.zfill(10))        # 00000Hello
# zfill() is useful for numbers
print("42".zfill(5))    # 00042
print("-42".zfill(6))   # -00042 (handles sign correctly)

Other Useful Methods

expandtabs()

text = "Name\tAge\tCity"
print(text.expandtabs(12))
# Name        Age         City

maketrans() and translate()

table = str.maketrans("aeiou", "12345")
text = "hello world"
print(text.translate(table))  # h2ll4 w4rld

removeprefix() and removesuffix() (Python 3.9+)

filename = "test_report.py"
print(filename.removeprefix("test_"))   # report.py
print(filename.removesuffix(".py"))     # test_report

Complete Reference Table

Category Method Description
Case upper() All uppercase
  lower() All lowercase
  title() Title Case
  capitalize() First char upper
  swapcase() Swap case
  casefold() Aggressive lowercase
Search find(sub) Index of first match (-1 if not found)
  rfind(sub) Index of last match
  index(sub) Like find but raises ValueError
  count(sub) Count occurrences
  startswith(s) Check prefix
  endswith(s) Check suffix
Modify replace(old, new) Replace substring
  strip() Remove edge whitespace
  lstrip() / rstrip() Remove left/right whitespace
  split(sep) Split into list
  join(list) Join list into string
  splitlines() Split by line breaks
Validate isdigit() All digits?
  isalpha() All letters?
  isalnum() All letters/digits?
  isspace() All whitespace?
  islower() / isupper() All lower/upper?
Align center(w) Center-align
  ljust(w) / rjust(w) Left/right-align
  zfill(w) Pad with zeros

Summary

  • Python strings have 40+ built-in methods
  • Case methods: upper(), lower(), title(), capitalize()
  • Search: find(), count(), startswith(), endswith()
  • Modify: replace(), strip(), split(), join()
  • Validate: isdigit(), isalpha(), isalnum()
  • All methods return new strings (strings are immutable)
  • Chain methods: " hello ".strip().upper() → "HELLO"

Next up: String Formatting Deep Dive →

Updated: