我有一个字符串。python中的字符串列表转换
s = '1989, 1990'
我要转换的是使用Python &列出我想作为输出,
s = ['1989', '1990']
是否有同任何一个最快的方式班轮?
我有一个字符串。python中的字符串列表转换
s = '1989, 1990'
我要转换的是使用Python &列出我想作为输出,
s = ['1989', '1990']
是否有同任何一个最快的方式班轮?
使用split method:
>>> '1989, 1990'.split(', ')
['1989', '1990']
但你可能想:使用replace
分裂由
删除空格 ''
这样:
>>> '1989, 1990,1991'.replace(' ', '').split(',')
['1989', '1990', '1991']
这将更好地工作,如果你的字符串是来自用户的输入,因为用户可能会忘记在逗号后打空格。
调用split
功能:
myList = s.split(', ')
print s.replace(' ','').split(',')
首先删除空格,然后用逗号分割。
这是一个更好的答案 - 更换所有空间可能会影响数据,剥离拆分项目是一个更好的主意。 – 2012-03-28 10:45:20
或者你可以使用正则表达式:
>>> import re
>>> re.split(r"\s*,\s*", "1999,2000, 1999 ,1998 , 2001")
['1999', '2000', '1999', '1998', '2001']
表达\s*,\s*
匹配零个或多个空白字符,一个逗号和零个或多个空白字符一次。
我创建了这个泛型方法:
def convertToList(v):
'''
@return: input is converted to a list if needed
'''
if type(v) is list:
return v
elif v == None:
return []
else:
return [v]
或许是为了你的项目非常有用。
converToList(s)
可能的重复[如何将字符串拆分为Python列表?](http://stackoverflow.com/questions/88613/how-do-i-split-a-string-into-a -list-python) – bernie 2012-03-28 15:05:49