Search code examples
stringpython-3.xliststring-literals

String to list when missing comma in string


I have kinda painted myself in corner by converting vectors fom a dataframe to str. My vectors now look like this [ -9.1676396 -171.8196878]. The problem is that they somehow lost the comma in the middle, used to be like this [ -9.1676396, -171.8196878]. Then, whenever I would need a list conversion I could do:

literal_eval('[ -9.1676396, -171.8196878]')

However this no longer works since I've lost the comma. My question is, how can I transform a string like this in a list? I also have to account for the fact that some may differ in spacing. Here is the type of edits I could have:

[ -9.1676396 -171.8196878 ]
[1.2904753 103.8520359]
[   21.2160437 -157.975203 ]

Solution

  • If you have line like:

    [ -9.1676396 -171.8196878 ]
    

    It can be easily converted to list of floats by follow code:

    [float(x) for x in '[ -9.1676396 -171.8196878]'.replace('[','').replace(']','').split()]
    

    This code removes [ and ] symbols, splits line with space as separator and converts resulting string parts into floats.