[英]Convert string representation of list to list when elements are not encased in quotes
Similar to Convert string representation of list to list but consider the elements in the list are not encased in quotes, eg类似于将列表的字符串表示形式转换为列表,但考虑到列表中的元素不包含在引号中,例如
x = '[a, b, c, ab, adc, defg]'
How could you convert this to a list of string elements in python?如何将其转换为 python 中的字符串元素列表?
['a', 'b', 'c', 'ab', 'adc', 'defg']
As it's a string, you can take the square brackets off and split by your delimiter:因为它是一个字符串,所以您可以去掉方括号并按分隔符分割:
>>> x = '[a, b, c, ab, adc, defg]'
>>> x[1:-1].split(', ')
['a', 'b', 'c', 'ab', 'adc', 'defg']
This should do the trick:这应该可以解决问题:
>>> x = '[a, b, c, ab, adc, defg]'
>>> [i.strip(',[]') for i in x.split()]
['a', 'b', 'c', 'ab', 'adc', 'defg']
But of course, this assumes this exact format and nothing else more complicated但是,当然,这假定了这种精确的格式,没有其他更复杂的了
Below以下
x = '[a, b, c, ab, adc, defg]'
l = x[x.find('[') + 1: x.find(']')].split(',')
print(l)
You could do following:您可以执行以下操作:
import re
x = '[a, b, c, ab, adc, defg]'
x = re.sub(r"[\[\]]", "", x)
split_x = x.split(',')
print(split_x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.