简体   繁体   English

当元素未包含在引号中时,将列表的字符串表示形式转换为列表

[英]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.

相关问题 当元素没有被引用时,将元组列表的字符串表示形式转换为列表 - Convert a string representation of a list of tuples to a list when elements are not quoted 将列表的字符串表示形式转换为列表 - Convert string representation of list into list 如何将Python列表中带单引号的字符串元素转为双引号 - How to convert string elements with single quotes to double quotes in a Python list 将列表的字符串表示形式转换为Python中的列表 - Convert string representation of list to list in Python 如何将列表的字符串表示形式转换为列表 - How to convert string representation of list to a list 将列表列表的字符串表示形式转换为 python 中的列表 - convert a string representation of a list of lists to a list in python 如何将没有双引号元素的列表的字符串表示形式转换为实际列表? - How to convert a string representation of a list without double quoted elements to an actual list? 将列表的字符串表示形式转换为字典 Python - Convert String representation of a List to a Dictionary Python 将颜色的字符串表示形式转换回列表 - Convert string representation of colors back to list 在 Python 中的二维列表的字符串表示中插入引号 - Inserting quotes into the string representation of a 2D list in Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM