Python - 将字符串拆分为参数

Python - Split Strings into parameters

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

input = "\"filename.txt\", 1234,8973,\"Some Description \""

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

预期输出应该是

['filename.txt', '1234', '8973', 'Some Description']

split 可以完成这项工作还是我需要正则表达式?

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

import csv

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

演示:

>>> 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']

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

>>> 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']

csv.reader() 对象将 iterable 作为第一个参数;我使用 str.splitlines() method 将一个(可能是多行的)字符串变成一个列表;如果您的输入字符串始终只有一行,您也可以只使用 [inputstring]

>>> [s.strip(' "') for s in input.split(',')]
['filename.txt', '1234', '8973', 'Some Description']

如果保证你引用的部分中没有出现逗号,就可以了。

你可以使用 Python map and lambda ..

In [9]: input = "\"filename.txt\", 1234,8973,\"Some Description \""
In [11]: input = map(lambda x: x.strip(), input.split(','))
In [14]: input = map(lambda x: x.strip('"'), input)
In [16]: input = map(lambda x: x.strip(), input)
In [17]: input
Out[17]: ['filename.txt', '1234', '8973', 'Some Description']

你可以这样做

li=input.split(",")

这会接你

li=['"filename.txt"', ' 1234', '8973', '"Some Description "']

然后相应地使用 ltrim 和 rtrim 有关详细信息,请参阅 How to trim whitespace (including tabs)?

使用 re 模块。

试试下面的代码:

import re
filter(lambda x: x != '', re.split(",| |\"", input))

输出将是:

['filename.txt', '1234', '8973', 'Some', 'Description']
map(str.strip, input.replace('"','').split(','))

你可以只使用eval()函数

input = "\"filename.txt\", 1234,8973,\"Some Description \""
>>> list(eval(input))
['filename.txt', 1234, 8973, 'Some Description ']