Py学习  »  Python

在python中,只在双引号后拆分字符串

Elec • 4 年前 • 1061 次点击  

我这里有一根这样的绳子:

"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"

是的,是的 双引号在 这个字符串。

现在我想把这根线分成几个部分 mystring.split(",") 我得到的是这个

"BLAX"

"BLAY"

"BLAZ

BLUBB"

"BLAP"

但我想要的是:

"BLAX"

"BLAY"

"BLAZ, BLUBB"

"BLAP"

我怎样才能做到这一点,同时我想保留双引号?我需要这个是因为我用的是toml文件。

解决方案: 谢谢@giacomo alzetta

我对正则表达式使用了split命令。也谢谢你的解释!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/46095
 
1061 次点击  
文章 [ 6 ]  |  最新文章 4 年前
Andy L.
Reply   •   1 楼
Andy L.    4 年前

你可以 replace split

s.replace('", ', '"|').split('|')

Out[672]: ['"BLAX"', ' "BLAY"', ' "BLAZ, BLUBB"', ' "BLAP"'] 
h4z3
Reply   •   2 楼
h4z3    4 年前

正如我在评论中所说,您可以在多个分隔符处拆分。逗号在引号和外部都有一个,但我们可以在 ", (添加了一个空格,这样我们就不必删除它;)

然后我们加上缺少的报价:

original = '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"'
[s if s.endswith('"') else s+'"' for s in original.split('", ')]

输出: ['"BLAX"', '"BLAY"', '"BLAZ, BLUBB"', '"BLAP"']

这种方法不使用正则表达式,因此速度更快。你也不需要玩什么正则表达式适合你的情况(我一般喜欢正则表达式,但我更喜欢智能拆分和操作)。

Adam.Er8
Reply   •   3 楼
Adam.Er8    4 年前

你可以分开 " 然后去掉不需要的剩余部分,用一个简单的list comp将所有内容用引号重新包装。

string = '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"'

parts = ['"{}"'.format(s) for s in string.split('"') if s not in ('', ', ')]

for p in parts:
    print(p)

输出:

"BLAX"
"BLAY"
"BLAZ, BLUBB"
"BLAP"
Rakesh
Reply   •   4 楼
Rakesh    4 年前

您也可以使用 csv 模块。

前任:

import csv

s = '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"' 
r = csv.reader(s, delimiter = ',', quotechar='"')
res = [j for i in r for j in i if j.strip()] 
print(res)  

输出:

['BLAX', 'BLAY', 'BLAZ, BLUBB', 'BLAP']
Andrej Kesely
Reply   •   5 楼
Andrej Kesely    4 年前

你可以使用 ast.literal_eval 然后添加 '"' 手动:

s = '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"'

from ast import literal_eval

data = literal_eval('(' + s + ')')

for d in data:
    print('"{}"'.format(d))

印刷品:

"BLAX"
"BLAY"
"BLAZ, BLUBB"
"BLAP"
Giacomo Alzetta
Reply   •   6 楼
Giacomo Alzetta    4 年前

可以使用正则表达式和 re.split 功能:

>>> import re
>>> re.split(r'(?<="),', '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"')
['"BLAX"', ' "BLAY"', ' "BLAZ, BLUBB"', ' "BLAP"']

(?<=") 方法 前面必须加上 " 但是 不包含在实际匹配中,因此只有 , 用于实际执行拆分。

你可以分开 ", 但那你就得把 现在不见了:

>>> '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"'.split('",')
['"BLAX', ' "BLAY', ' "BLAZ, BLUBB', ' "BLAP"']
>>> [el + ('' if el.endswith('"') else '"') for el in '"BLAX", "BLAY", "BLAZ, BLUBB", "BLAP"'.split('",')]
['"BLAX"', ' "BLAY"', ' "BLAZ, BLUBB"', ' "BLAP"']