Python Modify Strings
Modifying a string makes a new string with the changes. Python strings cannot change in place.
Make it loud
upper() returns a new string in capital letters. The first string stays as it was.
name = "ada"
print(name.upper())
print(name)Make it quiet
lower() returns a new string in small letters.
shout = "HELLO"
print(shout.lower())Trim the ends
strip() removes spaces from the start and the end.
text = " hi "
print(text.strip())Swap a word
replace() swaps every match for new text.
phrase = "I like tea"
print(phrase.replace("tea", "coffee"))Split into pieces
split() breaks text at spaces. The result is a list of the pieces.
name = "Ada Lovelace"
print(name.split())Example
name = " Ada Lovelace "
clean = name.strip()
parts = clean.split()
print(clean)
print(parts)
print(parts[0])
print(parts[1])Key points
- Immutable: a value that cannot be changed in place
- Method: a tool that belongs to a value, called with a dot
- Use upper() and lower() to change the case of letters
- Use strip() to remove spaces from both ends
- Use replace() to swap one piece of text for another
- Use split() to break a string into a list of pieces
In this example, name holds a messy name with extra spaces. strip() removes the spaces at both ends. The tidy text is saved in clean. split() breaks clean at its space into two pieces. print(clean) shows the tidy name. print(parts) shows the two pieces as a list. parts[0] is the first piece, Ada. parts[1] is the second piece, Lovelace.
Note
These methods never change the first string.
Save the result if you want to keep it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What happens when you run "Bo".upper()?