PYTHON / STRINGS
Creating and quoting strings
Create Python strings with single, double, and triple quotes, choose the delimiter that avoids escaping, and know when adjacent literals merge.
What you will learn
- Pick the quote style that lets you type apostrophes or quotes without escaping
- Use triple quotes for text whose line breaks are part of the data
- Recognise that two adjacent string literals merge into one at compile time
- Convert non-strings with str() instead of hand-quoting values
Understanding Creating and quoting strings
A quote character in Python source is a delimiter, not data. 'cat' and "cat" produce exactly the same object with exactly three characters, so len is 3 and the two compare equal. Python offers both styles for one practical reason: the delimiter cannot appear unescaped inside the literal, so you pick the one your text does not contain. "It's fine" needs no escaping, and 'She said "hi"' needs none either.
Triple quotes (''' or """) change one thing: the literal may span source lines, and every newline you type becomes a real newline character in the value. That makes them right for text where the line structure is part of the data, such as a block of SQL or help text, and wrong for text you merely want to wrap across lines for readability. If the opening """ is followed immediately by a line break, that break is the first character of the string, which is why a backslash at the end of the opening line is a common way to drop it.
For readability wrapping, Python has a separate mechanism: two or more string literals separated only by whitespace or a line break are joined by the parser into a single literal before the program runs. That is why 'one ' 'two' is one string, and also why a forgotten comma in a list of strings silently produces fewer, longer items instead of an error. This joining only works between literals; a variable next to a literal is a syntax error, and non-strings must go through str() first.
single = 'She said "hi"'
double = "It's fine"
triple = """line one
line two"""
print(single)
print(double)
print(triple)
print(len('ab'), len("ab"), 'ab' == "ab")
message = ('one part '
'second part')
print(message)
print(str(42) + '/' + str(3.5))
Quotes are only delimiters chosen to suit the text inside, while triple quotes and adjacent-literal joining are two different ways of dealing with long text.
Worked examples
The missing comma trap
Shows adjacent string literals being joined by the parser, and the silent bug that follows from a forgotten comma.
names = [
'alice',
'bob'
'carol',
]
print(names)
print(len(names))
joined = 'ab' 'cd'
print(joined)
Example explained
Line 1'bob' and 'carol' have no comma between them, so the parser treats them as one literal 'bobcarol'.
Line 2The list therefore has two elements, not three, and no error is raised at any point.
Line 3'ab' 'cd' shows the same rule used deliberately: whitespace between literals means join.
Line 4This joining happens while the code is compiled, so there is no runtime work involved.
Triple quotes and where the newlines land
Uses repr() to show exactly which newline characters a triple-quoted literal contains.
block = """\
first
second
"""
print(repr(block))
one_line = """no newline here"""
print(repr(one_line))
quoted = '''He said "it's fine"'''
print(quoted)
Example explained
Line 1The backslash after the opening """ cancels the line break, so the value starts at 'first'.
Line 2The break before the closing """ is kept, so the value ends with a newline.
Line 3A triple-quoted literal on one line contains no newline at all; the quotes add nothing.
Line 4Triple single quotes let both " and ' appear inside untouched.
Quoted digits are not numbers
Demonstrates that quoting is what makes a value a string, and str() is how other values become one.
n = 7
s = str(n)
print(s, type(s))
print('7' == 7)
print(repr(''), len(''))
Example explained
Line 1str(7) builds the one-character string '7'; printing it looks identical to printing 7.
Line 2'7' == 7 is False because a string and an int are never equal, however they display.
Line 3'' is a complete, valid string literal whose length is 0, not a missing value.
Line 4repr() is the tool to use when you need to see quoting and escapes rather than the text.
Important notes
Python has no separate character type; a one-character string like 'a' is an ordinary string of length 1.
A triple-quoted string written as the first statement of a module, class, or function becomes its docstring, so it is not merely a comment.
Common mistakes
Writing 'it's' with single quotes: the literal ends at the apostrophe and the line fails with a SyntaxError before anything runs.
Omitting a comma between string literals in a list or function call: the items merge silently, so a later len() or loop count is wrong with no error to point at.
Assuming a triple-quoted block starts at the first visible word: if the opening quotes are followed by a line break, the value begins with a newline and printed output gains a blank first line.
Try it yourself
Change, predict, then run
Store the text She replied, "it's late" in a variable using each of the three quoting styles that can hold it without escapes, then print len() of each to confirm all three values are identical.
Open the Python workspaceCheck your understanding
A list literal is written as ['red', 'green' 'blue'] with no comma after 'green'. What does the list contain, and why?
- Two items, 'red' and 'greenblue', because adjacent string literals are joined into a single literal when the code is compiled
- Three items, because Python inserts the missing comma between elements of a list
- Nothing: it raises a SyntaxError, since list elements must be separated by commas
- Two items, 'red' and 'green', because the trailing literal 'blue' is discarded
Show answer
Whitespace between two string literals means concatenation, so 'green' 'blue' is one literal and the list has two items. The SyntaxError option is tempting because commas are normally required, but here the parser sees a single valid element rather than two elements missing a separator, which is exactly why this bug is silent.