Python Forum
Help with converting strings to arrays - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help with converting strings to arrays (/thread-9903.html)



Help with converting strings to arrays - lwatson49 - May-03-2018

I am trying to read in comma delimited data and build some numerical arrays.

# get a comma delimited string
row = ['10,20,40,50']
print (', '.join(row))
a = (','.join(row))
print (a[3])

This is returning 2 as the value of a[3}. I want it to return a numeric 40. How do create the numeric array from a common delimited string?

Thanks in advance,
Larry


RE: Help with converting strings to arrays - ThiefOfTime - May-03-2018

Let us assume you can not be sure that each item is an integer and all are seperate through a comma.
The simplest solution assuming that each is an integer is:
row_arr = row[0].split(',')
row_arr = [int(value) for value in row_arr]
If you can not be sure that each is a string, you should consider regex:
import re
your_regex = re.compile('([0-9]+)')
row_array = row_array[0].split(',')
row_array = [int(your_regex.match(value).group(1)) for value in row_array if your_regex.match(value) is not None]
what this does is to check if you string is matching this pattern, which defines each number greater than 0. If you find a string like "a" your regex will return None and you may skip it :)


RE: Help with converting strings to arrays - lwatson49 - May-03-2018

Thanks, that nailed it!!