Strings
A string is a sequence of characters: letters, digits, spaces, symbols, even emoji. Strings are written in single or double quotes.
greeting = "Hello"
language = 'Python'
print(greeting, language)Multi-line strings
Triple quotes let a string span several lines; the line breaks are kept:
poem = """Roses are red,
Violets are blue,
Python is readable,
And so are you."""
print(poem)Joining and repeating
+ joins (concatenates) strings and * repeats them:
first = "Code"
second = "Mirai"
print(first + second)
print(first + " " + second)
print("-" * 20)Length
len() counts the characters, including spaces:
message = "Hello, world!"
print(len(message))
print(len(""))Checking what a string contains
The in operator tests whether one string appears inside another:
sentence = "Python is fun to learn"
print("fun" in sentence)
print("boring" in sentence)
print("python" in sentence) # case matters!
print("boring" not in sentence)Strings are immutable
Once created, a string cannot be changed in place. Operations always create a new string:
word = "cat"
word.upper() # makes "CAT" but we threw it away
print(word)
word = word.upper() # keep the new string
print(word)Trying to change a single character fails:
word = "cat"
word[0] = "b"To change part of a string, build a new one, for example "b" + word[1:], which uses slicing from the next lesson.
Comparing strings
print("apple" == "apple")
print("apple" == "Apple")
print("apple" < "banana") # alphabetical (dictionary) order
print("Zebra" < "apple") # capitals come before lower case!Strings compare character by character using their Unicode codes, and every capital letter has a smaller code than every lower-case letter. To compare without caring about case, compare a.lower() == b.lower().