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 because they are enclosed in quotation marks. In python you can use the function type to tell you what type it is.

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 "Hello world!"
  • print 123
  • print type("Hello World!")
        
>>> print type("Cisco Systems")
<type 'str'>
>>> print type(17)
<type 'int'>
        
    
        
>>> print """Bob's single "interface" is not configured"""
Bob's single "interface" is not configured
        
    
Console 1

                
            

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 concatenate that value. When working with some of Cisco IOS interface nomenclatures this becomes more problematic.

On the example on the right you can construct what a interface string reference based on real numeric values that we can iterate through ( when you learn that latter ). Using the str() python function you can take that numeric value and convert it to string to be presented in that string.

        
>>> print "Ethernet" + 1 + "/" + 12
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

>>> print "Ethernet" + str(1) + "/" + str(12)
Ethernet1/12
        
            

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.

Attempting to convert a string into a float or integer will cause a python exception.

        
>>> print( 3.14, int(3.14))
(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

                
            

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 various different quotation levels to encapsulated quotes including the triple quote. Another option is to also utilize the raw string construct print r'Some Text'

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.


>>> print 'C:\some\name'
C:\some
ame
>>> print r'C:\some\name'
C:\some\name

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.

Method Description Example
capitalize Capitalizes the first character in uppercase >>> "car".capitalize()
'Car'
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'
split Returns list of items split on value >>> "00:01:0c:15:15:15".split(":")
["00","01","0c","15","15","15"]
splitlines Returns separate lines in a string as list >>> "This router \nis having \nproblems".splitlines()
['This router ', 'is having ', 'problems']

For a complete list of the string methods please visit:

String Splicing and Indexes

Strings can also be indexed and sliced. If you have the word "Ethernet"[0] the interpreter will return just E. Using the negative in the position value starts the pointer in the reverse direction.

Slicing strings makes it possible to extract a section of a string based on a start and finish position. "Ethernet"[0:2]

        
>>> "Ethernet"[3]
'e'
>>> "Ethernet"[-1]
't'
>>> "Ethernet"[0:2]
'Et'
        
        

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

Whenever you are doing an assignment the name of the variable is on the left of the assignment 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 determine if two variables are the same. In Python this is accomplished by utilizing either a single equal sign = or double==.

        
>>> interface = "ethernet1/2"
>>> print interface
ethernet1/2

>>> module = 1
>>> port = 12
>>> print "ethernet" + str(module) + "/" + str(port)
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.

Variable names can be arbitrarily long. They must start with a letter or an underscore and can't contain spaces. In python it is also considered a bad practice to use uppercase letters with variables. Also case does matter and a variable that has a name of Car is not the same as car.

Some words can't be used in the assignment of variables. This is because these are Python keywords.

        
>>> module = 1
>>> port = 12
>>> port = port + 1
>>> print "ethernet" + str(module) + "/" + str(port)
ethernet1/13
        
        
andasassertbreakclasscontinue
defdelelifelseexceptexec
finallyforfromglobal ifimport
inislambdanonlocalnotor
passraisereturntrywhilewith
yieldTrueFalseNone  
Console 3

                
            

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 string based on variables.

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.

You can also utilize the same concept to create new variables based on values inserted via the format specifier

        
>>> interface = "eth1/1"
>>> print "interface %s" % ( interface )
interface eth1/1
        
        
        
>>> module = 1
>>> interface = 1
>>> print "interface %i/%i" % ( module , interface )
interface 1/1
        
        
        
>>> module =1
>>> interface = 1
>>> myint = "interface %i/%i" % (module , interface)
>>> print myint
interface 1/1
        
        
Character Output format Notes
d,i Signed decimal integer Value must be number
u Unsigned decimal integer Value must be number
o Unsigned octal integer Value must be number
x Unsigned hexadecimal integer (lowercase letters) Value must be number
X Unsigned hexadecimal integer (uppercase letters) Value must be number
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
f,F Floating-point value in decimal form Value must be number
c Single character Value can be integer or single-character string
r String Converts any value with repr
s String Converts any value with str
% Literal % character Consumes no value

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
"{0} {1} {2}".format("eth1/1","eth1/2","eth1/3") 'eth1/1 eth1/2 eth1/3'
"{2} {1} {0}".format("eth1/1","eth1/2","eth1/3") 'eth1/3 eth1/2 eth1/1'
interfaces=["eth1/1","eth1/2","eth1/3"]
"{0[0]} {0[1]} {0[2]}".format(interfaces)
'eth1/1 eth1/2 eth1/3'

You can also do conversions

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