Python Strings

Python strings are one of the Python data types. A string is a sequence of characters. In this lesson, you will learn how to create and manipulate strings in Python.

We’ll open Python so it shows the interpreter:

>>>

And then try some examples.

Double or Single Quotes

We create a string by enclosing characters inside single or double quotes. Here’s an example with double quotes:

>>> "hello world"

Will result in this output:

'hello world'

And an example with single quotes:

>>> 'hello world'

Will result in this output:

'hello world'

Both work and “hello world” is the exact same thing as ‘hello world’. What’s the difference then? You could pick one of the two when you want to use a single or double quote within the string. Let me show you an example:

>>> 'This is my router's output'

Will result in this output:

  File "", line 1
    'This is my router's output'
                       ^
SyntaxError: invalid syntax

In the code above, we get an invalid syntax error. Why? Python thinks the string ends with the single quote after the word “router”. We can work around this by using double quotes for our string:

>>> "This is my router's output"

Will result in this output:

"This is my router's output"

This solves our problem. We can also use this the other way around when we want to use a double quote within our string. When we switch to single quotes, we can use double quotes within our string:

>>> 'My router is the "best" there is'

Will result in this output:

'My router is the "best" there is'

Our string is now valid.

Escape character

Escaping a single or double quote within a string is possible with the examples above but we can also use the \ (backslash) as an escape character. Here is an example:

>>> 'My router is the \'best\' there is'
'My router is the "best" there is'

By using a \ before the character we want to escape, Python ignores the character and correctly prints the string. If you only need to escape a few characters, this is a good way to do it. If you have a string with many characters to escape, it might be easier to switch between single or double quotes to create your strings.

Triple Quote Multiline String

If you want a string that consists of more than one line, you can use triple quotes. Here is an example:

"""This is the output of R1:
Interface GigabitEthernet0/1
 IP address 192.168.1.1 255.255.255.0"""

When you paste this to the Python interpreter, it formats it like this:

>>> """This is the output of R1: 
... Interface GigabitEthernet0/1 
...  IP address 192.168.1.1 255.255.255.0""" 
...

It shows these ... dots to emphasize this is a triple quote multiline string.

And when you execute it, you get this:

'This is the output of R1:\nInterface GigabitEthernet0/1\n IP address 192.168.1.1 255.255.255.0'

The output above looks clunky. Between the lines, you can see the \n symbol. Python interprets this as a new line. If you want the string to look nice, you should use the print command. Here is an example:

>>> print("""This is the output of R1:
Interface GigabitEthernet0/1
IP address 192.168.1.1 255.255.255.0""")

And you’ll get this:

This is the output of R1:
Interface GigabitEthernet0/1
IP address 192.168.1.1 255.255.255.0

Because of the print command, Python processes the /n newline symbol and prints the second part of the string on a new line.

String Concatenation

In Python, we can concatenate (combine) strings with the + symbol. Here is a quick example:

>>> "Router " + "R1"

This is the output:

'Router R1'

This combines “Router ” and “R1” into “Router R1”. You can also multiply strings:

>>> "Error " * 4

This is the output:

'Error Error Error Error '

This shows the string multiple times.

Concatenation Errors

You can’t concatenate everything. When you try to concatenate a string and an integer, you get an error:

>>> "Error Code: " + 3

This is the output:

Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    "Error Code: " + 3
    ~~~~~~~~~~~~~~~^~~
TypeError: can only concatenate str (not "int") to str

Python tells us that we can’t concatenate a string and an integer. Hmm, too bad. There are two ways to work around this. The first option is to represent our integer as a string:

>>> "Error Code: " + "3"

This is the output:

'Error Code: 3'

This works, but it’s not always possible. What if the integer is returned from an external program? The data we receive is not always under our control.

Fortunately, Python can convert between different data types. With the str() function, we can convert something into a string. Let’s convert our integer into a string:

>>> "Error Code: " + str(3)

This is the output:

'Error Code: 3'

This solves our problem.

String Formatting

We can use string formatting to insert values into a string. There are two options. Let me show you both.

% Operator

This is the older method where we use the % operator. Here’s how it works:

  • The % within our string is a substitute.
  • The % operator at the end of the string formats a variable we specify with our string.

Let me show you an example:

>>> ip_address = "192.168.1.1"
>>> connect_msg = "We connect to: %s"
>>> print(connect_msg % ip_address)

This is the output:

We connect to: 192.168.1.1

In the code above, I used the %s operator to convert the value into a string. You can also do this with multiple values but you have to add the values between parentheses:

>>> ip_address = "192.168.1.1"
>>> hostname = "R1"
>>> connect_msg = "We connect to %s with IP: %s"
>>> print(connect_msg % (hostname, ip_address))

This is the output:

We connect to R1 with IP: 192.168.1.1

This is how we use the % operator. It supports many more options but the examples above suffice for most simple scripts.

Format() Method

The format() method is the newer way of inserting values into strings. Here’s how it works:

  • Within the string we use {} as a placeholder.
  • We append.format() to the end of the string and add the value we want to insert between the parentheses.

Here’s what it looks like:

>>> vlan = 200
>>> vlan_text = "We use VLAN: {}"
>>> print(vlan_text.format(vlan))

This is the output:

We use VLAN: 200

We can also do this for multiple values like this:

Unlock This Lesson for Free - No Credit Card Needed!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2778 Sign Ups in the last 30 days

Ask a question or start a discussion by visiting our Community Forum