← Intro to programming with Python
Strings: joining and repeating text
Glue text together with + and repeat it with *.
Text in Python is called a string, because it is a string of characters in a row. You can use double quotes or single quotes, as long as the start and end match. The + sign glues strings together (programmers call this concatenation) and * repeats a string. Why is this useful? Most messages a program shows are built from pieces: a greeting plus a name, a label plus a value.
first = "Maya"
last = 'Chen'
full = first + " " + last
print(full) # Maya Chen
print("ha" * 3) # hahaha
print("Level " + str(5))The " " in the middle adds the space between the names. str(5) turns the number 5 into the text "5" so it can be joined to another string.
Common mistake: joining text and a number with +. "Age: " + 15 gives a TypeError, because Python does not know whether you meant math or text. Write "Age: " + str(15), or use a comma in print().
Another common mistake: forgetting the space. "Maya" + "Chen" gives MayaChen.
Need an apostrophe in your text? Wrap the text in double quotes: "It's sunny" works fine.