在Python3.3中,从字符串创建一个列表

2024-04-18 22:12:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的字符串(包含n个元素):

input = 'John, 16, random_word, 1, 6, ...'

如何将其转换为这样的列表?我想把“,”作为分隔符。

output = [John, 16, random_word, 1, 6, ...]

Tags: 字符串元素列表inputoutputrandomjohnword
3条回答

使用split函数。

output = 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(',')中的字符串构成的列表。 这相当于

    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进行阴影处理。

你也可以在split', ',但是你必须确保逗号后面总是有空格(考虑换行符等)

你是说output = ['John', '16', 'random_word', '1', '6', ...]?你可以像output = inpt.split(', ')那样拆分它。这还会删除,之后的空白。

相关问题 更多 >