Strings

The first data type we will look at is the string. A string is a sequence of characters representing a text.

Strings come in many shapes and forms. They can be single or double quoted, and they can be multiline. Just remember that everything inside the quotes ("", '') is considered a string.

salute = 'Hello, World!'
salute = "Hello, World!"
salute = """Hello,
to
the
entire
World!"""

In the examples above we assign the string to a variable called salute. The variable can be used to reference the string later in the code. Triple quotes are used to create multiline-strings. This is useful when you want to write a long string that spans multiple lines.

E.g. when writing a long paragraph or a comment, or building a network configuration. In order to output the string, you can use the print() function.

But this seems like a pretty boring string, right? Let's spice it up a bit.

command_start = "switchport access vlan "
vlan_id = "11"
command = command_start + vlan_id
print(command)
switchport access vlan 11
vlan_id = "11"
command = f"switchport access vlan {vlan_id}"
print(command)
switchport access vlan 11
vlan_id = "11"
command = "switchport access vlan {}".format(vlan_id)
print(command)
switchport access vlan 11

String concatenation is a way to combine strings in Python. Only strings can be concatenated with other strings. More on that later. String interpolation is a way to format strings in Python. The f before the string tells Python to interpolate the variables inside the curly braces {}.

Now, let's look at a longer example that can be used to build a small network configuration.

This example includes getting input interactively from the user, using the input() function.

# single and double quotation marks are allowed e.g. to allow nested strings
question = 'enter "vlan" id: '

# we use the variable `question` instead of supplying a string in-line for the `input` function
vlan = input(question)

# the answer is saved as a string in the variable `vlan`
print("switchport mode access")
print("switchport access vlan {}".format(vlan))

# This is a comment - it is ignored by the Python interpreter
# Below is a multiline string - it is also a comment

"""
On a string with a placeholder you can use the format() method
the format method inserts other strings in the placeholder(s).
here we insert the vlan id we got from the user
"""

# introspection - printing the data type of the variable `vlan`
print(type(vlan))

TASK: Create a small configuration snippet with 2 or more placeholders

  • Use the input() function to get the required input from the user.
  • Use either f-strings or .format() to interpolate the variables into the string.
  • print() the configuration snippet.

Which method did you prefer? The f-string or the .format() method? Discuss why with a colleague.