Title: Parse delimited strings into lists with Python
Fairly regularly I need to convert a delimited string into a list of values. For example, I might want to the string "0.16; 0.15; 0.89; 0.02; 0.89; 0.39; 0.71; 0.32" into a list of floats.
This is pretty easy in Python. Simply use split to split the string into pieces. Then use a list comprehension to convert the pieces into whatever the data type you want.
Here's how this example parses three strings into lists of integers, floats, and strings.
s1 = '16; 15; 89; 02; 89; 39; 71; 32; 03; 27; 91'
s2 = '0.73 0.92 0.17 0.38 0.64 0.47 0.20 0.11 0.98'
s3 = 'RGC-DKJ-AKU-KJW-PQI-AKL-QIU-LAK-KAP-CML-AKD-LLF'
l1 = [int(value) for value in s1.split(';')]
l2 = [float(value) for value in s2.split()]
l3 = [value for value in s3.split('-')]
print(l1)
print(l2)
print(l3)
The code first defines three delimited strings. It then uses three statements to parse them. The first one, for example, splits the first string at semi-colons. It then uses a list comprehension that loops through the pieces and uses int to convert each piece into an integer.
The other two comprehensions are similar, although the third one doesn't use int or float or anything because it doesn't need to convert the pieces form strings to another data type.
The program finishes by displaying the lists.
It's not a very difficult example, but it can be handy under certain circumstances.
Download the example to experiment with it and to see additional details.
|