Loading lessons...
Modify Strings
Modify Strings
You can't change a string in place, but you can create modified copies with built-in methods.
Uppercase and lowercase
a = "Hello, World!"
print(a.upper()) # HELLO, WORLD!
print(a.lower()) # hello, world!
Remove whitespace
strip() removes spaces from the start and end:
a = " Hello, World! "
print(a.strip()) # "Hello, World!"
Replace
replace() swaps one piece of text for another:
a = "Hello, World!"
print(a.replace("H", "J")) # Jello, World!
Split
split() breaks a string into a list on a separator:
a = "Hello, World!"
print(a.split(",")) # ['Hello', ' World!']
Concatenate (join with +)
a = "Hello"
b = "World"
c = a + " " + b
print(c) # Hello World
Check what's in it
startswith()andendswith()test the edges.find()gives the index of a substring (or -1).count()counts occurrences.
s = "banana"
print(s.count("a")) # 3
print(s.find("nan")) # 2
Strings are immutable
None of these change the original string. They all return a new one.
TL;DR
upper(),lower(),strip(),replace(),split()return new strings.- Join strings with
+or" ".join(list). find(),count(),startswith()inspect text.- Strings never change in place.