字符串用特定字符串替换所有美元金额

String replace all dollar amounts with a specfic string

我需要用 python 中字符串中的“”标记替换美元金额。到目前为止,这是我想通的:

这是我的字符串:

s = 'Accounts and current portion of notes receivable, net of allowances of ,199 and ,506 at July 2, 2011 and October 2, 2010, respectively'

使用这个正则表达式我可以正确找到所有的美元金额。

re.findall(r"[$]{1}[\d,]+\.?\d{0,2}",s)

给我:

[',199', ',506']

但是,我想在原始字符串中用“”替换美元金额。我怎么做?

预期输出:

'Accounts and current portion of notes receivable, net of allowances of <amount> and <amount> at July 2, 2011 and October 2, 2010, respectively'

可能

re.sub(r"[$]{1}[\d,]+\.?\d{0,2}","<amount>",s)

会做你需要的...顺便说一句,如果你只需要一个,你不必指定 {1} 因为这是默认行为

您可以使用以下方式进行替换:

s1 = re.sub("$([\d,]+\.?\d{0,2})", '<amount>', s)
#              ^                ^

但是

s1 = re.sub("$([\d,]+(?:\.\d{2})?)", '<amount>', s)
#              ^      %         % ^
#  in between '^' matches the entire dollar amount
#  in between '%' matches the decimal part

可能会更好。

括号内的部分是匹配部分,它会被替换为您的替换字符串。找到美元符号后,我们获取以下所有数字和逗号。因此,插入符号标记的括号之间是被替换的匹配部分。小数处理部分略有调整。使用您的代码,您可以只匹配“。”或“.5”。上面的版本确保捕获小数点后跟两位数。另请注意,此十进制捕获位于非捕获括号内。但这没关系,因为非捕获括号仍在捕获括号内。有关详细信息,请参阅 https://docs.python.org/3/library/re.html