python regex分隔字符串中的列表子字符串

时间:2018-11-29 02:44:37

标签: python regex

我有一个像这样的字符串'[[20, 20.4,aa], [c, 10.5, eee]]'。 我的目的是将字符括在单引号中,并保持数字不变。

例如:

examples:
s1 = "[[20, 20.4, aa], [c, 10.5, eee]]"
s2 = "[[a , bg, 20], [cff, 20, edd]]"

required:
s1 = "[[20, 20.4,'aa'], ['c', 10.5, 'eee']]"
s2 = "[[a , 'bg', 20], ['cff', 20, 'edd']]"

到目前为止,我已经做到了:

s = '[[20, 20.4,a], [c, 10.5, e]]'

s = ''.join(["'"+ i + "'" if i.isalpha() else i for i in s])
s # "[[20, 20.4,'a'], ['c', 10.5, 'e']]"

但是它仅适用于单个字符。如果我有aa,它将给出'a''a',这是错误的。 如何解决该问题?

1 个答案:

答案 0 :(得分:2)

您可以使用sub

import re

s1 = '[[20, 20.4,aa], [c, 10.5, eee]]'
s2 = '[[a , bg,20], [cff, 20, edd]]'

rs1 = re.sub('([a-zA-Z]+)', r"'\1'", s1)
print(rs1)
rs2 = re.sub('([a-zA-Z]+)', r"'\1'", s2)
print(rs2)

输出

[[20, 20.4,'aa'], ['c', 10.5, 'eee']]
[['a' , 'bg',20], ['cff', 20, 'edd']]

模式([a-zA-Z]+)表示匹配一个或多个字母并将它们放在一组中,然后引用该组r"'\1'"并用单引号引起来。

相关问题