String in Python is:
sequence of characters enclosed in quotes
immutable ordered data type
Examples of strings:
In : 'Hello' Out: 'Hello' In : "Hello" Out: 'Hello' In : tunnel = """ ....: interface Tunnel0 ....: ip address 10.10.10.1 255.255.255.0 ....: ip mtu 1416 ....: ip ospf hello-interval 5 ....: tunnel source FastEthernet1/0 ....: tunnel protection ipsec profile DMVPN ....: """ In : tunnel Out: '\ninterface Tunnel0\n ip address 10.10.10.1 255.255.255.0\n ip mtu 1416\n ip ospf hello-interval 5\n tunnel source FastEthernet1/0\n tunnel protection ipsec profile DMVPN\n' In : print(tunnel) interface Tunnel0 ip address 10.10.10.1 255.255.255.0 ip mtu 1416 ip ospf hello-interval 5 tunnel source FastEthernet1/0 tunnel protection ipsec profile DMVPN
Strings can be summed. Then they merge into one string:
In : intf = 'interface' In : tun = 'Tunnel0' In : intf + tun Out: 'interfaceTunnel0' In : intf + ' ' + tun Out: 'interface Tunnel0'
You can multiply a string by a number. In this case, string repeats specified number of times:
In : intf * 5 Out: 'interfaceinterfaceinterfaceinterfaceinterface' In : '#' * 40 Out: '########################################'
The fact that strings are an ordered data type allows to refer to characters in a string by a number starting from zero:
In : string1 = 'interface FastEthernet1/0' In : string1 Out: 'i'
All characters in a string are numbered from zero. But if you need to refer to a character from the end, you can specify negative values (this time with 1).
In : string1 Out: 'n' In : string1[-1] Out: '0'
In addition to referring to a specific character you can make string slices by specifying a number range. Slicing starts with first number (included) and ends at second number (excluded):
In : string1[0:9] Out: 'interface' In : string1[10:22] Out: 'FastEthernet'
If no second number is specified, slice is until the end of string:
In : string1[10:] Out: 'FastEthernet1/0'
Slice last three character of string:
In : string1[-3:] Out: '1/0'
You can also specify a step in slice. For example, you can get odd numbers:
In : a = '0123456789' In : a[1::2] Out: '13579'
Or you can get all even numbers of string
In : a[::2] Out: '02468'
Slices can also be used to get a string in reverse order:
In : a = '0123456789' In : a[::] Out: '0123456789' In : a[::-1] Out: '9876543210'
a[:] give the same result but double colon makes it possible to indicate that not every element should be taken, but for example every second element.
len function allows you to get number of characters in a string:
In : line = 'interface Gi0/1' In : len(line) Out: 15
Function and method differ in that method is tied to a particular type of
object and function is generally more universal and can be applied to
objects of different types. For example,
len function can be applied
to strings, lists, dictionaries and so on, but
only applies to strings.