Reputation: 101
I am new to Python and love it. However, I have a problem and hope someone can help.
I have a string of values separated by commas and want to use a loop to individually process each of the values in turn.
e.g.
string = '1,2,3,4,5,6,'
I want to take the first value '1' and process it before moving on to the next value.
Upvotes: 1
Views: 74
Reputation: 37249
In the case above, you can use the split
method to split a string by commas and then iterate through the resulting list:
In [1]: s = '1,2,3,4,5,6,'
In [2]: s.split(',')
Out[2]: ['1', '2', '3', '4', '5', '6', '']
In [3]: for i in s.split(','):
...: if i:
...: print i
...:
...:
1
2
3
4
5
6
split
returns a list, so what we do here is iterate through the resulting list and then check to see if the field is empty or not; it not process. We do this check because your string ends in a ,
, which as you can see returns an empty string. Also note that this splits on all commas - not just those that separate values.
For the case above, that should be fine, but in the case where you want to do more advanced handling of CSV information, the csv
module provides numerous options for doing so. For example:
In [1]: import csv
In [2]: s = '1,2,3,"four, five",6'
In [3]: for item in csv.reader([s]):
...: print item
...:
...:
['1', '2', '3', 'four, five', '6']
Here we use the csv
module to read the string, and the item
returned represents the comma-separated string, but with the special "four, five"
value still treated as one value. However note that in the case of a single string, this returns a single list comprised of the comma-separated string elements. As @JonClements points out, a clean way to iterate through the elements themselves is to call next
on csv.reader([s])
, which will return the list itself:
In [1]: import csv
In [2]: s = '1,2,3,"four, five",6'
In [3]: for item in next(csv.reader([s])):
...: print item
...:
...:
1
2
3
four, five
6
Upvotes: 3