Lesson 6 of 30 · Working With Data
Strings
Work with text in Python. Join strings, measure them, pick out characters, change case and build messages with f-strings.
- 7 min read
- Beginner
- Reviewed
- How to join and repeat strings
- How to get the length of a string and pick out single characters
- Useful string methods such as upper(), strip() and replace()
- How to build messages with f-strings
Strings are text
A string is any text inside quotation marks. Names, sentences, email addresses and even a whole book can be stored as a string.
greeting = "Hello" language = 'Python' print(greeting) print(language)
Joining and repeating
The + operator joins strings. This is called concatenation. Python does not add spaces for you, so include them yourself.
first = "Ada"
last = "Lovelace"
full_name = first + " " + last
print(full_name)
print("ha" * 3)How long is a string?
len() counts the characters in a string, including spaces and punctuation.
word = "Python" sentence = "I love AI!" print(len(word)) print(len(sentence))
Picking out characters
Each character has a position called an index. Python starts counting at 0, not 1.
| P | y | t | h | o | n |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
Use square brackets to get a character. A negative index counts from the end.
word = "Python" print(word[0]) print(word[1]) print(word[-1])
You can also take a slice, a piece of the string. word[0:3] starts at index 0 and stops before index 3.
word = "Python" print(word[0:3]) print(word[2:]) print(word[:2])
String methods
A method is an action that belongs to a value. You call it with a dot. These are the ones you will use most.
text = " Machine Learning "
print(text.upper())
print(text.lower())
print(text.strip())
print(text.replace("Machine", "Deep"))
print(text.strip().title())upper()andlower()change the case.strip()removes spaces from both ends.replace(old, new)swaps one piece of text for another.title()capitalises the first letter of each word.
Checking what a string contains
The word in tests whether one string appears inside another. The answer is True or False.
email = "ada@example.com"
print("@" in email)
print("gmail" in email)
print(email.endswith(".com"))f-strings: the best way to build messages
An f-string lets you put variables straight into text. Write the letter f before the opening quotation mark, then put variable names inside curly brackets.
name = "Ada"
age = 36
print(f"{name} is {age} years old.")
print(f"Next year {name} will be {age + 1}.")
print(f"Pi is roughly {3.14159:.2f}")You can put any calculation inside the brackets. Adding :.2f after a number shows it with two decimal places.
Join first and last with a space between them and print the result as Ada Lovelace.
first = "ada" last = "lovelace" # Print the full name with capital letters: Ada Lovelace
If word = "Python", what is word[1]?
Summary
+joins strings and*repeats them.len()returns the number of characters.- Indexes start at 0. Slices such as
word[0:3]return part of a string. - Methods such as
upper(),strip()andreplace()return a new string. - f-strings put variables inside text:
f"Hello, {name}".
Next, your programs will start asking the user questions.
Finished reading? Tick it off to track your progress.