【问题标题】:How to concatenate only consecutive numbers in a string?如何仅连接字符串中的连续数字?
【发布时间】:2018-03-23 15:10:49
【问题描述】:

我有一个带有文本和数字的字符串,例如:

string = "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56"

我只想将连续的数字放在一起,如下所示:

newString = "Hello this is 123456 a string for test 12345678. I want to merge 123456"

如何检测数字,检查它们是否连续并将它们连接起来?

谢谢!

【问题讨论】:

  • 我首先尝试获取如下数字: string = "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56" [int(s) for s in str.split() if s.isdigit()]

标签: python string numbers concatenation


【解决方案1】:

这是使用正则表达式的一种方式:

import re
text = "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56"
newText = re.sub(r"(?<=\d)\s(?=\d)", '', text)
print(newText)
#'Hello this is 123456 a string for test 12345678. I want to merge 123456'

说明

我们正在做的是用空字符串替换任何被数字包围的空格。

  • (?&lt;=\d) 表示数字的正向后视 (\d)
  • \s 表示匹配空格字符
  • (?=\d) 表示正向预测数字

【讨论】:

    【解决方案2】:

    使用re.sub() 函数和特定的正则表达式模式:

    import re
    
    s =  "Hello this is 123 456 a string for test 12 345 678. I want to merge 12 34 56"
    result = re.sub(r'(\d+)\s+(\d+?)', '\\1\\2', s)
    
    print(result)
    

    输出:

    Hello this is 123456 a string for test 12345678. I want to merge 123456
    

    【讨论】:

      猜你喜欢
      • 2016-07-14
      • 2019-04-13
      • 2021-07-19
      • 2016-02-16
      • 2013-03-31
      • 1970-01-01
      • 2012-08-16
      • 1970-01-01
      • 2011-02-12
      相关资源
      最近更新 更多