Basic Python: split string into list and slice it (Examples)


basic-python-split-slice-strings

A very common problem in programming is splitting a string or a stream into it’s elements, convert it to a list and then take parts of that list for further processing. Using Python – this is a piece of cake. Anyway in my daily work I often see sysadmins and engineers writing shell scripts utilizing tools like sed, awk, cut, complex regex and some wild piping kung fu to do this kind of work. Mostly these scripts are far away from being readable … I think (and very often say) more people should start to learn and use Python – especially for system administration and automation tasks. Today we take a close look at the basic Python split function …

 

Example: Split a string into it’s words and pop the last element

 

You can watch the video first – and then play with the example.
You will find the code below the video …

 

                                                               
#!/usr/bin/python  
# python split example                                                                                                                       

my_string = '''    This is a multiline python string to demonstrate splitting and slicing and                                             
other complex operations!                                                                                                                 
Compared to shell scripts, str     operations can be very simple and intuitive.                                                           
The old school \t\t sys admin is "programming" in bash.                                                                                   
The hipster devops guy is using python.                                                                                                   
\t\n                                                                                                                                      
'''

# just print that string:                                                                                                                 
print my_string

# now we want to split that string into it's words/elements                                                                               
#                                                                                                                                         
# Reference: https://docs.python.org/2/library/stdtypes.html#str.split                                                                    
#                                                                                                                                         
# If split is called without arguements:                                                                                                  
# runs of consecutive whitespace (and tabs etc) are regarded as a single separator, and the result                                        
# will contain no empty strings at the start or end if the string has leading or                                                          
# trailing whitespace. Consequently, splitting an empty string or a string                                                                
# consisting of just whitespace with a None separator returns [].                                                                         
my_list = my_string.split()

# and print it ... see that all spaces, tabs etc, are removed                                                                             
print my_list

# now we want to have the last word of that list                                                                                          
# for this we will just use the python sliceing notation                                                                                  
# the number in brackets references the last element of the list                                                                          
last_item = my_list[-1]
print
print 'Last item is:', last_item
print

# here are some other examples:        
# count starts at 0                                                                                                    
print 'First item is:', my_list[0]       

# slice a sub list with [from:to]                                                                             
print 'Elements 3-6 are:', my_list[2:5]   

# also works counting backwards                                                               
print 'Last 3 items are:', my_list[-3:]                                                                    

# now some complex string operations in one line                                                                                 
# String to list, and back to string                                                                                   
print 'The moral of the story is:', ' '.join(my_string.split()[27:])
          

Running that code will result in the following output:

    This is a multiline python string to demonstrate splitting and slicing and 
other complex operations!
Compared to shell scripts, str     operations can be very simple and intuitive.
The old school 		 sys admin is "programming" in bash.
The hipster devops guy is using python.
	
 

['This', 'is', 'a', 'multiline', 'python', 'string', 'to', 'demonstrate', 'splitting', 'and', 'slicing', 'and', 'other', 'complex', 'operations!', 'Compared', 'to', 'shell', 'scripts,', 'str', 'operations', 'can', 'be', 'very', 'simple', 'and', 'intuitive.', 'The', 'old', 'school', 'sys', 'admin', 'is', '"programming"', 'in', 'bash.', 'The', 'hipster', 'devops', 'guy', 'is', 'using', 'python.']

Last item is: python.

First item is: This
Elements 3-6 are: ['a', 'multiline', 'python']
Last 3 items are: ['is', 'using', 'python.']
The moral of the story is: The old school sys admin is "programming" in bash. The hipster devops guy is using python.

 

Ok, this is it about the Python split function. If you want to learn more about python – you might want to start with a book? What are the best books to learn python?