Python - 将字符串拆分为参数

Den*_*nis 1 python string split numbers

我是Python的新手,我有一个字符串拆分问题,我需要帮助

input = "\"filename.txt\", 1234,8973,\"Some Description \""
Run Code Online (Sandbox Code Playgroud)

input 包含字符串和数字,并且可能存在前导和尾随空格的情况

预期产量应该是

['filename.txt', '1234', '8973', 'Some Description']
Run Code Online (Sandbox Code Playgroud)

可以拆分完成工作还是需要正则表达式?

Mar*_*ers 8

使用csv模块来处理这样的输入; 它处理引用,可以教导前导空格,之后可以删除尾随空格:

import csv

reader = csv.reader(inputstring.splitlines(), skipinitialspace=True)
row = next(reader)  # get just the first row
res = [c.strip() for c in row]
Run Code Online (Sandbox Code Playgroud)

演示:

>>> import csv
>>> inputstring = '"filename.txt", 1234,8973,"Some Description "'
>>> reader = csv.reader(inputstring.splitlines(), skipinitialspace=True)
>>> row = next(reader)
>>> [c.strip() for c in row]
['filename.txt', '1234', '8973', 'Some Description']
Run Code Online (Sandbox Code Playgroud)

这有一个额外的好处,你可以在值中使用逗号,前提是它们被引用:

>>> with_commas = '"Hello, world!", "One for the money, two for the show"'
>>> reader = csv.reader(with_commas.splitlines(), skipinitialspace=True)
>>> [c.strip() for c in next(reader)]
['Hello, world!', 'One for the money, two for the show']
Run Code Online (Sandbox Code Playgroud)

csv.reader()对象采用iterable作为第一个参数; 我使用该str.splitlines()方法将(可能多行)字符串转换为列表; [inputstring]如果你的输入字符串总是只有一行,你也可以使用它.