2024-04-18 22:12:14 发布
网友
我有一个这样的字符串(包含n个元素):
input = 'John, 16, random_word, 1, 6, ...'
如何将其转换为这样的列表?我想把“,”作为分隔符。
output = [John, 16, random_word, 1, 6, ...]
使用split函数。
output = input.split(', ')
您可以使用input.split(','),但正如其他人所指出的,您必须处理前导和尾随空格。可能的解决方案是:
input.split(',')
不带regex:
In [1]: s = 'John, 16, random_word, 1, 6, ...' In [2]: [subs.strip() for subs in s.split(',')] Out[2]: ['John', '16', 'random_word', '1', '6', '...']
我在这里所做的是使用一个list comprehension,在这个列表中,我通过调用^{}方法,创建了一个元素由s.split(',')中的字符串构成的列表。 这相当于
s.split(',')
strings = [] for subs in s.split(','): strings.append(subs) print(subs)
使用regex:
In [3]: import re In [4]: re.split(r',\s*', s) Out[4]: ['John', '16', 'random_word', '1', '6', '...']
另外,不要使用input作为变量名,因为这样会对the built-in function进行阴影处理。
input
你也可以在split上', ',但是你必须确保逗号后面总是有空格(考虑换行符等)
split
', '
你是说output = ['John', '16', 'random_word', '1', '6', ...]?你可以像output = inpt.split(', ')那样拆分它。这还会删除,之后的空白。
output = ['John', '16', 'random_word', '1', '6', ...]
output = inpt.split(', ')
,
使用split函数。
您可以使用
input.split(',')
,但正如其他人所指出的,您必须处理前导和尾随空格。可能的解决方案是:不带regex:
我在这里所做的是使用一个list comprehension,在这个列表中,我通过调用^{} 方法,创建了一个元素由
s.split(',')
中的字符串构成的列表。 这相当于使用regex:
另外,不要使用
input
作为变量名,因为这样会对the built-in function进行阴影处理。你也可以在
split
上', '
,但是你必须确保逗号后面总是有空格(考虑换行符等)你是说
output = ['John', '16', 'random_word', '1', '6', ...]
?你可以像output = inpt.split(', ')
那样拆分它。这还会删除,
之后的空白。相关问题 更多 >
编程相关推荐