Variables
Variables
Values
In Python a value could be something like a word or number that is manipulated by the program
that you write. These can be of various types like numbers and strings. Strings can be identified
>>> print type("Cisco Systems")
because they are enclosed in quotation marks. In python you can use the function type to tell you
<type 'str'>
what type it is. >>> print type(17)
<type 'int'>
With single and double quoted strings you can contain in themselves the oppposite. So a string that
needs a single quote inside can be encapsulated in double "Bob's interface eth1/2" . If you
quote the string inside a triple quote, then you can include any combination inside. """Bob's
single "interface" is not configured"""
You can utilize the Console below to do some exercises around this concept. Enter for yourself: >>> print """Bob's single "interface" is not configure
d"""
Bob's single "interface" is not configured
print "Hello world!"
print 123
print type("Hello World!")
Console 1
Run
In python the type of the value is important because some operations can't be done unless both
types are of the same class. So you couldn't add a string and a integer together if you wanted to
>>> print "Ethernet" + 1 + "/" + 12
concatenate that value. When working with some of Cisco IOS interface nomenclatures this
Traceback (most recent call last):
becomes more problematic. File "<input>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
On the example on the right you can construct what a interface string reference based on real
>>> print "Ethernet" + str(1) + "/" + str(12)
numeric values that we can iterate through ( when you learn that latter ). Using the str() python
Ethernet1/12
function you can take that numeric value and convert it to string to be presented in that string.
You can also convert the types of digits you want to input as either INT or FLOAT. Entering a
numeric number that has decimal value into a INT will cause python to round the number.
>>> print( 3.14, int(3.14))
Attempting to convert a string into a float or integer will cause a python exception. (3.14, 3)
>>> print(3.0, int(3.1))
(3.0, 3)
>>> print(float(3.14), int(3.14))
(3.14, 3)
>>> print(type(float(3.14)))
<type 'float'>
Console 2
Run
Strings
In computer programing strings are one of the more complicated entities. While they are simple to construct, they are more complex to manipulate. In networking we find
ourselves many times manipulating strings parsing output of devices. In that context a tool in programing known as regular expressions come into play ( more on that later ).
For strings there are some manipulations that are of interest. When working with strings you always
need to take into consideration the need escape characters. As was mentioned you can utilize the >>> print 'C:\some\name'
C:\some
various different quotation levels to encapsulated quotes including the triple quote. Another option
ame
is to also utilize the raw string construct print r'Some Text' >>> print r'C:\some\name'
C:\some\name
In the example on the right you can see that the \n in that line was interpreted as a new line
character. The same expression inside a raw derivate prints correctly.
Strings also can be repeated with the * operator. An example of this is to repeat a word and then
manipulate it with addition.
>>> print 3 * "Test" + "Out"
TestTestTestOut
In Python almost everything is an object. And because of this Strings are also objects to the interpreter. Since the string is an object it has an associated set of methods
available to it. These are accessible via the . that is included after the string.
The list of methods available to the string object is long, here is a summary of some to provide understanding.
find Search a string and return the lowest index point >>> "Ethernet1/1".find("net")
5
upper Replaces all string chacters with upper case versions >>> "why is this all lower".upper()
'WHY IS THIS ALL LOWER'
splitlines Returns separate lines in a string as list >>> "This router \nis having \nproblems".splitlines()
['This router ', 'is having ', 'problems']
Python Reference
https://docs.python.org/2/library/stdtypes.html#string-methods
Slicing strings makes it possible to extract a section of a string based on a start and finish position.
"Ethernet"[0:2]
Variables
One of the most powerful functions of any programming language is the ability to manipulate
variables. When you assign a value to a variable it is called an assignment
>>> interface = "ethernet1/2"
Whenever you are doing an assignment the name of the variable is on the left of the assignment >>> print interface
ethernet1/2
operator. In Python (as with many languages) the equal sign is utilized for this purpose. It is
important to understand though that the assignment operator (equal sign) can also be utilized to >>> module = 1
>>> port = 12
determine if two variables are the same. In Python this is accomplished by utilizing either a single
>>> print "ethernet" + str(module) + "/" + str(port)
equal sign = or double == . ethernet1/12
In the same way that you can add two numbers print 1 + 2 you can also add variables. Looking
at this example we take the port variable and add 1 to it.
>>> module = 1
Variable names can be arbitrarily long. They must start with a letter or an underscore and can't >>> port = 12
>>> port = port + 1
contain spaces. In python it is also considered a bad practice to use uppercase letters with >>> print "ethernet" + str(module) + "/" + str(port)
variables. Also case does matter and a variable that has a name of Car is not the same as car . ethernet1/13
Some words can't be used in the assignment of variables. This is because these are Python
keywords.
and as assert break class continue
Console 3
module = 1
port = 10
port = port + 1
print "ethernet" + str(module) + "/" + str(port)
Run
Another important concept to understand with strings is the format specifier. This is something
that you will utilize heavily in Python. The format specifier makes it possible to insert elements of a
>>> interface = "eth1/1"
string based on variables.
>>> print "interface %s" % ( interface )
interface eth1/1
As you had done previously we can use the format specifier to achieve the same goal but it
provides more detail and flexibility in your work. Since you can specify the variable type in the
format specifier you can simplify how the values of variables are interpreted and printed.
In both examples you can see that we have both of strings and integers used to build the string that
contains what a configuration interface identifier looks like in IOS. >>> module = 1
>>> interface = 1
You can also utilize the same concept to create new variables based on values inserted via the >>> print "interface %i/%i" % ( module , interface )
interface 1/1
format specifier
>>> module =1
>>> interface = 1
>>> myint = "interface %i/%i" % (module , interface)
>>> print myint
interface 1/1
e Floating-point value in exponential form (lowercase e for exponent) Value must be number
E Floating-point value in exponential form (uppercase E for exponent) Value must be number
While this method has it's origins in the C language world, Python has started using a new method that is more elaborate. In most of the cases the syntax is similar to the old
%-formatting, with the addition of the {}. For example:
Old New
myint = "interface %i/%i" % (module , interface) myint = "ethernet {}/{}".format( var1, var2)
The formatter can also manipulate the order of the representation and even reference a list ( we will discuss lists later ).
Code Output
Code Output
"int: {0:d}; hex: {0:x}; bin: {0:b}".format(255) 'int: 255; hex: ff; bin: 11111111'
"int: {0:d}; hex: {0:#x}; bin: {0:#b}".format(255) 'int: 255; hex: 0xff; bin: 0b11111111'
There is more information available at https://docs.python.org/2.7/library/string.html#new-string-formatting . We will be covering more details in examples as we progress.
Console 4
module = 1
port = 10
port = port + 1
print "ethernet" + str(module) + "/" + str(port)
Run