Python将字符串拆分为参数

2024-04-20 07:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

预期产出应为

^{2}$

split可以做这个工作还是我需要正则表达式?在


Tags: 字符串txtinput情况数字somedescriptionfilename
3条回答

您可以使用Pythonmaplambda来实现这一点。。在

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

使用^{} 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]

演示:

^{pr2}$

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

>>> 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作为第一个参数;我使用^{} method将一个(可能是多行)字符串转换成一个列表;如果您的输入字符串总是只有一行,您也可以使用[inputstring]。在

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

如果可以保证引用的部分中不出现逗号,那么就可以了。在

相关问题 更多 >