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

标签 python python-3.x

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

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

如何将其转换为这样的列表?我希望“,”成为分隔符。

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

最佳答案

您可以使用 input.split(',') 但正如其他人指出的那样,您必须处理前导和尾随空格。可能的解决方案是:

  • 没有正则表达式:

    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(',') 中的字符串组成,方法是调用 strip他们的方法。 这相当于

    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。 .

您也可以在 ', '拆分,但您必须绝对确保逗号后始终有一个空格(考虑换行符等)

关于python - 在 Python 3.3 中从字符串创建列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13867274/

相关文章:

python - 尝试在 Windows 8.1 上安装 kivy

python - 使用 Tensorflow 后端的 CTC Beam 搜索

python - 自定义数据生成器

mysql - 来自 mysql 的 python 中的 JSON 和额外的键值对

Python ValueCan3 模块/脚本

python-3.x - 我什么时候应该使用 pytest --import-mode importlib

python-3.x - Dash python plotly实时更新表

python - 映射 Pandas 数据框中的值范围

Python 检查是否为质数

python-3.x - TF 2.0 - 方法 estimator.model_to_estimator( ) 失败但 model.fit 适用于 tf.keras 创建的模型