Badatprogramming
Badatprogramming

Reputation: 11

How to re.split this line

Want to split this line :

  1,        0.625,           0.,          2.5

to get output string like :

a = ["   " , "1" , "," , "     " , "0.625" , "," , "   " , "0." , "," , "    " , "2.5"] 

so I could change value of for example a[0] = 2 and at end get this :

  2,        0.625,           0.,          2.5

Is it possible? Please help

Upvotes: 0

Views: 64

Answers (1)

tobias_k
tobias_k

Reputation: 82899

You can use re.split and put a group (...) around the things to split, e.g. ,|\s+. This way, the separators are themselves part of the result. This produces some empty groups, though, between comma and space, which you have to filter out.

>>> s = "  1,        0.625,           0.,          2.5"
>>> [x for x in re.split(r"(,|\s+)", s) if x]
['  ', '1', ',', '        ', '0.625', ',', '           ', '0.', ',', '          ', '2.5']

Note, however, that if your goal is to replace values and keep some sort of tabular layout, this is more complicated than needed. Also, it does not work well if the new value has a different number of digits. Instead, you could just split by ,, and when you replace a value, rjust the new value to the same width as the old value.

>>> vals = s.split(",")
>>> vals[2] = str(3.1415).rjust(len(vals[2]))
>>> ','.join(vals)
'  1,        0.625,       3.1415,          2.5'
>>> s
'  1,        0.625,           0.,          2.5'

Upvotes: 1

Related Questions