Python Strings

So we've seen numbers, but what about text? If you want to use text in Python, you need to quote it, like this:

>>> 'Hello, World'
'Hello, World'

Because of the quotes, Python understands this is a sequence of characters and not a command, number, or variable. Such a sequence is called a string in the field of computer science.

A string is a sequence of characters

Just like with numbers, some of the operators work on strings too. Try it with the following expressions:

>>> 'a' + 'b'
>>> 'ab' * 4
>>> 'a' - 'b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'
  • The plus operator glues two strings together.
  • The multiplication operator repeats our string.
  • The minus operator doesn't work on a string and produces an error. If you want to remove parts of a string, there are other methods that you'll learn about later on.

Single or double quotes?

We've used single quotes, but Python accepts double-quotes too:

>>> "a" + "b"

As you can see from its answer, Python itself prefers to use single quotes. It looks more clear, and Python tries to be as clear and well readable as it can. So why does it support both? It's because it allows you to use strings that contain a quote.

In the first example below, we use double quotes, hence there's no problem with the single quote in the word it's. In the second example, however, we try to use single quotes. Python sees the quote in the word "it's" and thinks this is the end of the string. The following letter "s" causes a so-called syntax error: your language syntax is not correct, and Python doesn't know what to do next:

>>> mystring = "It's a string, with a single quote!"
>>> mystring = 'It's a string, with a single quote!'
  File "<stdin>", line 1
    mystring = 'It's a string, with a single quote!'
SyntaxError: invalid syntax

There's another way around this problem, called escaping. You can escape a special character, like a quote, with a backward slash:

>>> mystring = 'It\'s an escaped quote!'
>>> _

You can also escape double quotes inside a double-quoted string:

>>> mystring = "I'm a so-called \"script kiddie\""
>>> _

So which one should you use? It's simple: always opt for the option in which you need the least amount of escapes because they make your strings less readable.

If you liked this page, please share it with a fellow learner: