SyntaxStudy
Sign Up
Python String Methods — Part 1
Python Beginner 8 min read

String Methods — Part 1

String Methods — Part 1

Python strings have dozens of built-in methods. The most commonly used ones deal with case, whitespace, splitting, and joining.

Case Methods

s = "  Hello, World!  "
print(s.upper())     # "  HELLO, WORLD!  "
print(s.lower())     # "  hello, world!  "
print(s.title())     # "  Hello, World!  "
print(s.swapcase())  # "  hELLO, wORLD!  "

Strip Methods

print(s.strip())     # "Hello, World!"
print(s.lstrip())    # "Hello, World!  "
print(s.rstrip())    # "  Hello, World!"

Split & Join

csv = "a,b,c,d"
parts = csv.split(",")   # ['a', 'b', 'c', 'd']
joined = "-".join(parts) # "a-b-c-d"
words = "one two three".split()
print(words)  # ['one', 'two', 'three']
Example
s = "  hello, world!  "
print(s.strip())          # "hello, world!"
print(s.strip().upper())  # "HELLO, WORLD!"
parts = "a,b,c".split(",")
print("-".join(parts))    # a-b-c
Pro Tip

split() with no argument splits on any whitespace and removes empty strings — very handy for parsing user input.