Chapter 4
Working with Text
Strings Are Sequences
You already know that Python calls a text input(), and placed them inside
This chapter looks inside a string.
Text in a particular order
A string is an ordered sequence of characters. Each letter, digit, space, and punctuation mark has a position.
The string "Python!" contains these characters in this order:
P y t h o n !
Changing the order creates a different string. "Python!" and "!Python" contain the same seven characters, but they are not the same text.
Spaces count too. The string "Python Land" contains a space between the two words. That space is a real character even though it is mostly invisible on the screen.
Quotation marks mark the boundaries
Python accepts either double or single quotation marks around an ordinary string:
course = "Python Fundamentals"
language = 'Python'
The opening and closing marks must match. The quotation marks belong to the code, not to the stored text.
Run this example:
The output does not include the quotation marks.
Choose quotes that fit the text
Double quotation marks are convenient when the text contains an apostrophe:
message = "Python isn't magic."
Single quotation marks are convenient when the text contains double quotes:
message = 'She said, "Hello."'
In the second example, the double quotation marks are part of the stored text. The single quotation marks mark the string’s boundaries.
Sometimes the text contains both kinds of mark, or you need a line break inside it. The next lesson introduces a precise way to write those characters.
The empty string
A string can contain no characters at all:
empty_message = ""
This is called the empty string. It is still a string value. It simply has no characters between its quotation marks.
An empty string is different from a string containing one space:
empty = ""
one_space = " "
That distinction will matter when you clean user input and when a program checks whether text is present.
Which line stores the text Erik's course without a syntax error?
A useful mental model
Think of a string as text with stable character order. In later lessons, you will ask for its length, retrieve a character by position, take a section of it, and produce transformed versions.
You are not learning a completely new value type. You are learning what the familiar string type can do.
Task
Run the example, complete the quiz, and make sure you can explain why spaces and punctuation are characters too. Then press Next to continue.