Skip to main content
 首页 » 编程设计

python之在 python 中按 ","拆分

2025年05月04日10over140

我想用逗号“,”分割一个字符串

例如:

"hi, welcome"  I would like to produce ["hi","welcome"] 

但是:

"'hi,hi',hi" I would like to produce ["'hi,hi'","hi"] 
 
"'hi, hello,yes','hello, yes','eat,hello'" I would like to produce ["'hi, hello,yes'","'hello, yes'","'eat,hello'"] 
 
"'hiello, 332',9" I would like to produce ["'hiello, 332'","9"] 

我不认为可以使用 .split() 函数,有谁知道我可以用正则表达式做到这一点的方法吗?

请您参考如下方法:

您可以将 csv 模块与 quotechar 参数一起使用,或者您可以将您的输入转换为使用更标准的 " 字符作为引号字符。

>>> import csv 
>>> from cStringIO import StringIO 
>>> first=StringIO('hi, welcome') 
>>> second=StringIO("'hi,hi',hi") 
>>> third=StringIO("'hi, hello,yes','hello, yes','eat,hello'") 
>>> fourth=StringIO("'hiello, 332',9") 
>>> rfirst=csv.reader(first,quotechar="'") 
>>> rfirst.next() 
['hi', ' welcome'] 
>>> rsecond=csv.reader(second,quotechar="'") 
>>> rsecond.next() 
['hi,hi', 'hi'] 
>>> rthird=csv.reader(third,quotechar="'") 
>>> rthird.next() 
['hi, hello,yes', 'hello, yes', 'eat,hello'] 
>>> rfourth=csv.reader(fourth,quotechar="'") 
>>> rfourth.next() 
['hiello, 332', '9'] 
 
>>> second=StringIO('"hi,hi",hi') # This will be more straightforward to interpret. 
>>> r=csv.reader(second) 
>>> r.next() 
['hi,hi', 'hi'] 
>>> third=StringIO('"hi, hello,yes","hello, yes","eat,hello"') 
>>> r=csv.reader(third) 
>>> r.next() 
['hi, hello,yes', 'hello, yes', 'eat,hello']