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

In simpler terms, a string is a piece of text. And just like with numbers, some of the operators work on Python 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 Python strings together.
  • The multiplication operator repeats our Python string the given number of times.
  • The minus operator doesn’t work on a Python 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 around a string as well:

>>> "a" + "b"

Note that these are not two single quotes next to each other. It’s the character that’s often found next to the ‘enter’ key on your keyboard. You need to pres shift together with this key to get a double quote.

As you can see from its answer, Python itself seems to prefer 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 string’s end. 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 Python strings less readable.

String Length

A very common operation in is to get the string length. This can be done with the len() function like this:

>>> len("I wonder how long this string will be...")
>>> _

Share this