[英]string to list conversion in python
I have a string. 我有一个字符串。
s = '1989, 1990'
I want to convert that to list using python & i want output as, 我想使用python将其转换为list并且我希望输出为,
s = ['1989', '1990']
Is there any fastest one liner way for the same? 有没有最快的一个班轮方式相同?
Use the split method : 使用拆分方法 :
>>> '1989, 1990'.split(', ')
['1989', '1990']
But you might want to: 但你可能想:
As such: 因此:
>>> '1989, 1990,1991'.replace(' ', '').split(',')
['1989', '1990', '1991']
This will work better if your string comes from user input, as the user may forget to hit space after a comma. 如果您的字符串来自用户输入,这将更好地工作,因为用户可能忘记在逗号后命中空格。
调用split
功能:
myList = s.split(', ')
print s.replace(' ','').split(',')
首先删除空格,然后用逗号分割。
Or you can use regular expressions: 或者您可以使用正则表达式:
>>> import re
>>> re.split(r"\s*,\s*", "1999,2000, 1999 ,1998 , 2001")
['1999', '2000', '1999', '1998', '2001']
The expression \\s*,\\s*
matches zero or more whitespace characters, a comma and zero or more whitespace characters again. 表达式
\\s*,\\s*
再次匹配零个或多个空白字符,逗号和零个或多个空白字符。
i created generic method for this : 我为此创建了通用方法:
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]
Maybe it is useful for your project. 也许它对你的项目有用。
converToList(s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.