Loading lessons...
String Methods
String Methods
Strings come with a rich toolbox of methods. Here are the ones you'll use most.
Case and spacing
s = " Hello World "
s.upper() # ' HELLO WORLD '
s.lower() # ' hello world '
s.strip() # 'Hello World'
s.capitalize() # ' Hello world '
s.title() # ' Hello World '
s.swapcase() # ' hELLO wORLD '
Search and replace
s = "Hello, World!"
s.find("World") # 7
s.index("World") # 7
s.count("o") # 2
s.replace("World", "Python") # 'Hello, Python!'
s.startswith("He") # True
s.endswith("!") # True
Checks (return True or False)
s = "123"
s.isalnum() # True (letters or digits)
s.isalpha() # False (digits are not letters)
s.isdigit() # True
s.islower() # False
s.isupper() # False
s.isspace() # False
Split and join
"a,b,c".split(",") # ['a', 'b', 'c']
"-".join(["a", "b"]) # 'a-b'
Padding and centering
"42".zfill(5) # '00042'
"hi".center(6) # ' hi '
Remember
Methods return new strings. The original is never modified.
TL;DR
- Case: upper, lower, capitalize, title, swapcase.
- Search: find, index, count, startswith, endswith, replace.
- Checks: isalnum, isalpha, isdigit, islower, isupper.
- Tools: split, join, zfill, center, strip.