Home > other >  Convert string to list of strings in python
Convert string to list of strings in python

Time:10-18

I have a string extracted from a .csv which has this format:

str = "[point, contextual, point]"

What I wanna do is convert it to a list in the format:

str = ["point", "contextual", "point"]

How can I do it? I tried with json.loads(str) but I got the error:

json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

CodePudding user response:

Try this code:

string = "[point, contextual, point]"
print(string[1:-1].split(', '))

Outputs:

['point', 'contextual', 'point']

Tell me if its okay for you...

CodePudding user response:

You could use this expression : str[1:-1].split(", ")

By the way it is not recommended to give a variable the name of a python type.

CodePudding user response:

you could use:

my_str = "[point, contextual, point]"
my_str[1:-1].split(', ') # remove first and last characters ([]) and split on ", "

NB. don't use str as a variable name, this overwrites the str builtin

CodePudding user response:

Because that's not a valid JSON string, the json.loads doesn't work. You need to do it manually and you can not use json module for the string you have.

st = "[point, contextual, point]"
lst = st[1:-1].split(', ')

On a side note, don't use str as a vairable: that's a builtin

CodePudding user response:

You can try this:

>>> st = "[point, contextual, point]"
>>> st[1:-1]
[point, contextual, point]

>>> st[1:-1].split(',')
['point', ' contextual', ' point'] # <- you have space

>>> list(map(lambda x: x.strip(), st[1:-1].split(',')))
['point', 'contextual', 'point']

why not split(', ')?

>>> st = "[point,   contextual,     point]"
>>> st[1:-1].split(', ') 
['point', '  contextual', '    point']

>>> list(map(lambda x: x.strip(), st[1:-1].split(',')))
['point', 'contextual', 'point']

CodePudding user response:

I suggest you use yaml:

import yaml
s = "[point, contextual, point]"
s = yaml.load(s, Loader=yaml.FullLoader)
print(s)

Output

['point', 'contextual', 'point']

Note:

yaml is a third party module to install it do (at the command line):

pip install pyyaml 

The yaml version of the code snippet above is 5.4.1

  • Related