Strings
Programming Languages · Python Basics · 12 min
Work with text: join it, fill it in with f-strings, pick out letters and change it.
Single or double quotes
Text in Python is called a string. You can wrap it in double quotes "hi" or single quotes 'hi'. Both work the same.
Pick the one that doesn't clash with your text:
print("It's sunny")
print('He said "wow"')
Print
It's raining.Print
She said "hi"(with the double quotes showing).
Joining strings
+ glues strings together. This is called joining. Python doesn't add spaces for you, so add them yourself:
word = "sun" + "flower" # "sunflower"
hi = "Hi " + "Bo" # "Hi Bo"
Create
full_nameby joiningfirst, a space" "andlast.Print
full_name.
f-strings
Joining with + gets messy fast. An f-string is easier: put f before the quotes, then drop variables in with curly brackets {}.
food = "pie"
print(f"I love {food}!") # I love pie!
You can put maths inside the brackets too: {2 * 3}.
Use an f-string to print
Sam is 12 years old.Use an f-string with
{age + 1}to printNext year Sam will be 13.
Length, letters and slices
len(text) counts the characters. Each character has a position called an index, starting at 0.
word = "cat"
print(len(word)) # 3
print(word[0]) # c
print(word[0:2]) # ca
word[0:2] is a slice: it starts at index 0 and stops before index 2.
Print the length of
word.Print the first letter of
word.Print the slice
word[0:4].
Changing case and replacing
Strings come with built-in tools called methods. You use them with a dot:
pet = "Rex"
print(pet.upper()) # REX
print(pet.lower()) # rex
print(pet.replace("R", "T")) # Tex
They give you a new string and leave the original alone.
Print
msgin capitals with.upper().Print
msgin small letters with.lower().Print
msgwith"Cats"replaced by"Dogs".
Put it together: a username maker
Make a username from someone's name: the first letter of their first name plus their last name, all in small letters. Grace Hopper becomes ghopper.
Create
usernamefromfirst[0]andlast, made lowercase with.lower().Use an f-string to print
Welcome, Grace! Your username is ghopper.Print
It has 7 letters, usinglen(username)for the number.
More in Python Basics
Previous: Numbers and Maths · Next: Conditionals