String Examples

Try typing these two examples exactly as they're written, with quotes around them, into the python Shell (click here if you've forgotten where to find it) and see what you get:

>>> "puppy dog"

>>> "Hello!"

Now try typing this example without quotes and hit Enter:

>>> apple

What’s the result? Did you get an error message?

We'll talk about these error messages a little later on, but for now we've learned a new rule about Python and strings:

Rule: If you want Python to read a string, it must be inside quotes.

Try some of these other examples:

>>> "apple"

>>> "What's for dinner?"

>>> "3 + 5"

It looks like numbers, or math expressions, can also be strings - as long as they're inside quotes!

There's one other thing you might have noticed. See that second-to-last example, the one asking "What's for dinner?" ?

That string has a single quote, or an apostrophe, inside it. And that's fine, because the quotes on the outside are double quotes.

But you can also wrap a string in single quotes - Python treats both of these expressions the same way:

>>> 'banana'

'banana'

>>> "banana"

'banana'

Suppose you have a string with an apostrophe in it. If you want to put that inside single quotes, you can escape the apostrophe - that is, tell Python that you meant for it to be part of the string:

>>> 'What\'s for dinner?'

"What's for dinner?"

Otherwise, Python thinks that apostrophe is supposed to be the end of the string:

>>> 'What's for dinner?'

File "<stdin>", line 1

'What's for dinner?'

^

SyntaxError: invalid syntax