Loading lessons...
Strings
Strings
Strings are text. In Python, a string is surrounded by single or double quotes.
print("Hello") # double quotes
print('Hello') # single quotes
Quotes inside strings
- Use double quotes if your text contains a single quote:
"It's fine". - Use single quotes if your text contains a double quote:
'She said "hi"'.
Assign a string to a variable
a = "Hello"
print(a) # Hello
Multi-line strings
Use three quotes (single or double) for text that spans several lines:
a = """One line.
Two lines.
Three lines."""
print(a)
Strings are arrays of characters
Python has no char type. A single character is just a string of length 1. You can grab one with square brackets:
a = "Hello, World!"
print(a[1]) # e
Remember: counting starts at 0, so a[0] is the first character.
Loop through a string
A for loop visits each character:
for x in "banana":
print(x)
Length
len() returns the number of characters:
a = "Hello, World!"
print(len(a)) # 13
Check for a word
Use in and not in to test whether text appears:
txt = "The best things in life are free!"
print("free" in txt) # True
print("free" not in txt)# False
TL;DR
- Strings use single or double quotes; be flexible with quotes inside.
- Triple quotes make multi-line strings.
s[0]is the first character (0-indexed).len()gives length;inchecks for text.