简体   繁体   English

在Python 3.3中从字符串创建列表

[英]Create a list from string, in Python 3.3

I have a string like this (with n number of elements): 我有一个这样的字符串(具有n个元素):

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

How can I convert it to a list like this? 如何将其转换为这样的列表? I would like ',' to be a separator. 我想将','用作分隔符。

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

You can use input.split(',') but as others have noted, you'll have to deal with leading and trailing spaces. 您可以使用input.split(',')但正如其他人指出的那样,您必须处理前导和尾随空格。 Possible solutions are: 可能的解决方案是:

  • without 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', '...'] 

    What I did here is use a list comprehension , in which I created a list whose elements are made from the strings from s.split(',') by calling the strip method on them. 我在这里所做的是使用列表 s.split(',') ,在其中创建了一个列表,该列表的元素是通过对s.split(',')的字符串调用strip方法来构成的。 This is equivalent to 这相当于

     strings = [] for subs in s.split(','): strings.append(subs) print(subs) 
  • with regex : 正则表达式

     In [3]: import re In [4]: re.split(r',\\s*', s) Out[4]: ['John', '16', 'random_word', '1', '6', '...'] 

Also, try not to use input as variable name, because you are thus shadowing the built-in function . 另外,请尽量不要使用input作为变量名,因为这样会掩盖内置函数

You can also just split on ', ' , but you have to be absolutely sure there's always a space after the comma (think about linebreaks, etc.) 您也可以只对', ' split ,但必须绝对确保逗号后始终有一个空格(考虑换行符等)。

you mean output = ['John', '16', 'random_word', '1', '6', ...] ? 您的意思是output = ['John', '16', 'random_word', '1', '6', ...] you could just split it like output = inpt.split(', ') . 您可以像output = inpt.split(', ')一样拆分它。 this also removes the whitespaces after , . 这也是后删除空格,

使用分割功能。

output = input.split(', ')

If I understand correctly, simply do: 如果我理解正确,只需执行以下操作:

output = input.split(',')

You will probably need to trim each resulting string afterwards since split does not care about whitespaces. 之后,您可能需要修剪每个结果字符串,因为split并不关心空格。

Regards, Matt 问候,马特

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM