Quiz
Warm-up from lesson 1-2: which line correctly prints the word hello?
Strings, line by line
Most of the data real programs handle is text: usernames, chat messages, search queries, email subjects, file names. An engineer's average day involves far more reading, checking, and assembling of text than fancy math, which is why strings get their own lesson before anything else.
A string is any piece of text your program works with: a name, a sentence, an emoji, even "12345" if you mean it as text rather than a number. You met strings in lesson 1-2. Now some useful details.
Each print produces one line of output, and the interpreter runs your lines top to bottom. So three prints make three lines, in order:
print("first") print("second") print("third")
Python accepts either double quotes "like this" or single quotes 'like this'. They mean the same thing. Pick one style and stay consistent (this course uses double quotes).
Strings also work with +. Between two strings, + produces a new string: the first immediately followed by the second. Joining strings this way is called concatenation:
print("door" + "bell")
That prints doorbell. Note + adds no space — concatenation joins the strings exactly as they are, so if you want a space you must put one inside a string yourself.
Code exercise · python
Run this three-line program. Notice the output lines appear in the same top-to-bottom order as the code.
Quiz
What does print("rain" + "bow") output?
Code exercise · python
Your turn. Write a program that prints these three lines exactly, in this order: Code is just text. Computers follow it exactly. You are the author.
Two more string tools
Repetition. Between a string and a whole number, * produces the string repeated that many times. Python reuses the multiplication symbol because repeating is repeated addition: "ha" * 3 means "ha" + "ha" + "ha". Engineers use this for things like separator lines in reports and padding in tables.
Quotes inside quotes. A double-quoted string ends at the next double quote, so "He said "hi"" confuses Python — it thinks the string ended before hi. Two clean fixes: wrap the string in single quotes when the text contains double quotes, or put a backslash before the inner quote (\"), which tells Python "this quote is part of the text, not the end of the string":
print('It said "hello" to me.') print("It said \"hello\" to me.")
Both lines print the same sentence, quotes included.
Code exercise · python
Run it. The first line shows repetition, the second shows a double quote surviving inside a string.
Code exercise · python
Your turn. Print a divider line of exactly 20 dashes using string repetition (one short print line — do not type 20 dashes by hand).