Skip to main content
 首页 » 编程设计

Python之将字符串拆分为参数

2025年05月04日27qq78292959

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

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

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

预期输出应该是

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

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

请您参考如下方法:

使用 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]。