【问题标题】:Replace substrings in python with the length of each substring用每个子字符串的长度替换python中的子字符串
【发布时间】:2014-12-08 22:03:58
【问题描述】:

如何替换子字符串,比如以大写字母开头的单词,以及该子字符串的长度,可能使用正则表达式。

例如: 使用正则表达式"\b[A-Z]+[a-z]*\b"

“他必须去纽约”

应该变成这样:

“2 到 3 4”

我使用它的实际场景有点不同,但我认为这个场景更清晰。

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    您可以使用re.sub 来接受可调用对象。每次找到不重叠的模式时,都会使用匹配对象调用该可调用对象。

    >>> s = "He got to go to New York"
    >>> re.sub(r'\b([A-Z][a-z]*)\b', lambda m: str(len(m.group(1))), s)
    '2 got to go to 3 4'
    

    【讨论】:

      【解决方案2】:

      这不是那么简洁,但如果您想避免使用正则表达式和 lambda,您可以编写如下内容:

      string = "He got to go to New York"
      string = string.split()
      
      for word in range(len(string)):
          if string[word][0].isupper():
              string[word] = str(len(string[word]))
      
      print(" ".join(string))
      

      【讨论】:

      • 这会因数字/标点符号而失败。例如:He got to New York, the most .. city.
      猜你喜欢
      • 2017-12-06
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 2019-12-01
      • 1970-01-01
      • 2018-04-01
      • 2013-07-10
      • 2016-09-17
      相关资源
      最近更新 更多