简体   繁体   English

字符串列出python中的转换

[英]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 list comprehensions : 使用列表推导

s = '1989, 1990'
[x.strip() for x in s.split(',')]

Short and easy. 简单易行。

Additionally, this has been asked many times! 此外,这已被问过很多次了!

Use the split method : 使用拆分方法

>>> '1989, 1990'.split(', ')
['1989', '1990']

But you might want to: 但你可能想:

  1. remove spaces using replace 使用替换删除空格

  2. split by ',' 由','拆分

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.

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