从 Python 中的子字符串中删除逗号
Remove comma from substring in Python
字符串如下:
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%'
我想删除此子字符串 ",455.85"
中的逗号,但不删除其他逗号。
我试过了但是失败了:
import re
pattern = r'$\d(,)'
re.sub(pattern, '', s)
为什么这不起作用?
你需要一个积极的后视断言,即匹配一个逗号,如果它前面是 $
(注意 $
需要转义为 $
),然后是一个数字(\d
)。尝试:
>>> s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%'
>>> pattern = r'(?<=$\d),'
>>> re.sub(pattern, '', s)
'AUDC,AUDIOCODES COM,+55,27.49,26.47,"55.85",(.10),(.10),-3.71%'
import re
pattern = r"($\d+),"
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%'
print(s)
s = re.sub(pattern, r'', s)
print(s)
输出:
AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%
AUDC,AUDIOCODES COM,+55,27.49,26.47,"55.85",(.10),(.10),-3.71%
但它不适用于“$1,455,789.85”
字符串如下:
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%'
我想删除此子字符串 ",455.85"
中的逗号,但不删除其他逗号。
我试过了但是失败了:
import re
pattern = r'$\d(,)'
re.sub(pattern, '', s)
为什么这不起作用?
你需要一个积极的后视断言,即匹配一个逗号,如果它前面是 $
(注意 $
需要转义为 $
),然后是一个数字(\d
)。尝试:
>>> s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%'
>>> pattern = r'(?<=$\d),'
>>> re.sub(pattern, '', s)
'AUDC,AUDIOCODES COM,+55,27.49,26.47,"55.85",(.10),(.10),-3.71%'
import re
pattern = r"($\d+),"
s = 'AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%'
print(s)
s = re.sub(pattern, r'', s)
print(s)
输出:
AUDC,AUDIOCODES COM,+55,27.49,26.47,",455.85",(.10),(.10),-3.71%
AUDC,AUDIOCODES COM,+55,27.49,26.47,"55.85",(.10),(.10),-3.71%
但它不适用于“$1,455,789.85”