2

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)

Fabio
  • 635
  • 6
  • 17
  • 4
    As a general point, it's best not to name something `str` as that's the name of the built-in string type. – sj95126 Oct 17 '21 at 14:59
  • Refer to the link below for a guideline: https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list – Sadegh Rahmani Oct 17 '21 at 15:02

6 Answers6

2

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

mozway
  • 194,879
  • 13
  • 39
  • 75
2

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.

hpchavaz
  • 1,368
  • 10
  • 16
2

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

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

Try this code:

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

Outputs:

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

Tell me if its okay for you...

Ghost Ops
  • 1,710
  • 2
  • 13
  • 23
1

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']
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
1

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

ThePyGuy
  • 17,779
  • 5
  • 18
  • 45