【问题标题】:How to replace a string by a variation of itself?如何用自身的变体替换字符串?
【发布时间】:2017-04-28 15:47:53
【问题描述】:

这个想法是用它们自己替换数字,但其中的任何逗号 (",") 从也有用于分隔句子的逗号的文本中删除。

来自 -> "This is a test with the number 21,938 followed by another sentence, with a coma"

收件人 -> "This is a test with the number 21938 followed by another sentence, with a coma"

【问题讨论】:

  • @Prune 我不这么认为,那是因为如果您只有数字作为自己的字符串,而不是较大字符串中间的数字。 OP 只想删除数字中的逗号,而不是字符串中的所有逗号。
  • @RandomDavis 没错。
  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的编码人员编写代码,但他们通常只有在发布者已经尝试自己解决问题时才会提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask
  • @Claudia 每当我看到请求代码的努力不足时,我都会将其发布。就像评论说的那样,对你尝试过的和出了什么问题表现出努力。就我发布的内容而言,代表或没有代表对我来说毫无意义。

标签: python regex


【解决方案1】:
import re

text = "A long sentence, with commas, some in 10,000,000.00, some not."

re.sub(r'(?<=\d),(?=\d)', '',text)
# 'A long sentence, with commas, some in 10000000.00, some not.'

我们查找逗号,,其前面和后面直接跟一个数字(\d)。我们不想捕获将被替换的组中的数字,所以我们使用:

(? 如果字符串中的当前位置以 在当前位置结束的 ... 的匹配。这称为 积极的后向断言。

(?=...)
匹配 if ... 匹配下一个,但不消耗任何 细绳。这称为前瞻断言。

参考Regular expression syntax

【讨论】:

  • 我不知道lookbehind和lookahead方法。谢谢。
【解决方案2】:

您可以使用正则表达式捕获后跟逗号的 3 位数字分组,然后动态替换它们:

重新导入

def RemoveCommas(string):
    numberRegex = re.compile(r'([0-9]{1,3},)')
    mo = numberRegex.findall(string)

    for innerString in mo:
        string = string.replace(innerString, innerString[:-1])

    print(string)

那么,如果我拨打以下电话:

RemoveCommas('Hi, this is a number: 123,456,789 and here, is a trailing comma.')

我得到这个结果:

Hi, this is a number: 123456789 and here, is a trailing comma.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    • 2021-08-03
    • 2011-10-23
    • 1970-01-01
    相关资源
    最近更新 更多