Sign InCoursewareNuggetsTutorials AboutClassesCodePad

Strings in Python

Values like "100" and "37.6" look like numbers, but they are actually strings because they are in quotation marks. In our previous examples, strings are in double quotes. What if we need to use quotation marks inside a string? When Python sees a quotation mark, it looks for the next matching quotation mark on that line and sees everything in between as the string value. The following example causes an error, because Python sees a string bounded by two double quotes ("The boy said, "). It doesn't understand the extra stuff afterwards.

"The boy said, "It's not a tiger. It's a bobcat!"" 

For this reason, strings in Python can be enclosed in either single quotes ('), double quotes ("), or three of each (''' or """). Double-quoted strings can contain single quotes inside them. Single-quoted strings can have double quotes inside them. Usually we use double quotes when single quotes appear in the string, as in "Crush's favorite color"; and use single quotes when there are double quotes in the string, as in 'Tali says "Hello!"'.

In some situations, we need to indicate that a quotation mark is part of the sentence as opposed to the end of the string. We can do so by using the escape character \ in front of the quotes that we want Python to understand.

print("The boy said, \"It's not a tiger. It's a bobcat!\"") print('The boy said, "It\'s not a tiger. It\'s a bobcat!"')

Another way is to use triple-quoted strings (strings enclosed with three quotes), which can contain either single or double quotes. It can even span multiple lines. We have already seen some examples in Unit 2 when we learned print( ) in Python.

print('''"What're your favorite animals?" Asked Tali.''') print('''"My favorite animals are dogs, horses, and ... turtles!" Exclaimed Andrew.''')

© CS Wonders·About·Classes·Cheatsheet