Strings
In this tutorial, we'll represent and work with text.
A string is text. In Python, strings are written inside quotes:
name = "Ada"
message = 'Hello'
Single quotes and double quotes both work. The important thing is that the opening and closing quotes match.
What Strings Are Used For
Strings are used for names, messages, email addresses, labels, passwords, file paths, and any other text.
first_name = "Grace"
last_name = "Hopper"
print(first_name)
print(last_name)
Joining Strings
You can join strings with +:
first_name = "Grace"
last_name = "Hopper"
full_name = first_name + " " + last_name
print(full_name)
Output:
Grace Hopper
The " " is a string containing one space. Without it, the names would run together.
String Methods
Strings come with useful methods. A method is an action attached to a value.
word = "python"
print(word.upper())
print(word.capitalize())
print(word.count("p"))
Output:
PYTHON
Python
1
The original string does not change unless you store the result:
word = "python"
word = word.upper()
print(word)
Indexing Strings
Each character has a position. Python starts counting at 0.
word = "code"
print(word[0])
print(word[1])
Output:
c
o
Common Mistake
Numbers inside quotes are strings:
age = "12"
print(age + age)
Output:
1212
Python joins the text. It does not add the number. To do maths, convert it with int() first.
Practice
Create a variable for your full name. Print it normally, in uppercase, and print how many characters it contains using len().