Computer Science · Ch 8 — Strings
Strings
Strings
A string is a sequence built out of one or more Unicode characters. Because Unicode covers far more than the English alphabet, a character here can be anything representable in text — a letter, a digit, a whitespace character, or any other symbol. What makes a string a sequence is that these characters sit in a fixed order, each at its own indexed position.
Creating a string
A string is created by enclosing its characters in quotes, and Python accepts three interchangeable quoting styles:
- single quotes —
'...' - double quotes —
"..." - triple quotes —
'''...'''or"""..."""
All three produce exactly the same kind of value. The following four variables therefore hold the same string:
>>> s1 = 'Namaste, Python!'
>>> s2 = "Namaste, Python!"
>>> s3 = """Namaste, Python!"""
>>> s4 = '''Namaste, Python!'''
Each of s1, s2, s3 and s4 is a string variable with the identical value 'Namaste, Python!'. The choice between single and double quotes is purely a matter of convenience — for instance, a string that itself contains an apostrophe is easier to write inside double quotes.
Triple quotes span multiple lines
The special power of triple quotes is that the string they enclose may extend across more than one line. A single- or double-quoted string must begin and end on the same line, but a triple-quoted string keeps going until the matching triple quote is found:
>>> s3 = """Namaste, Python!
learning strings is
the first step"""
>>> s4 = '''Namaste, Python!
learning strings is
the first step'''
Here the line breaks typed inside the quotes become part of the stored string itself. This makes triple quoting the natural way to hold a paragraph, a multi-line message, or any text whose layout matters.
What the rest of the chapter covers
With strings created, the chapter proceeds through:
- accessing individual characters through indexing (Section 8.2.1) and the fact that strings are immutable (Section 8.2.2); …