【问题标题】:Capture repeated characters and split using Python [duplicate]使用 Python 捕获重复字符并拆分 [重复]
【发布时间】:2018-05-22 19:32:08
【问题描述】:

我需要使用重复的字符来拆分字符串。

例如:

我的字符串是“howhowhow”

我需要输出为“如何、如何、如何”。

我不能在我的 reg exp 中直接使用“how”。因为我的输入不同。我应该检查字符串是否重复字符并且需要拆分该字符。

【问题讨论】:

标签: python regex


【解决方案1】:
import re

string = "howhowhow"

print(','.join(re.findall(re.search(r"(.+?)\1", string).group(1), string)))

输出

howhowhow -> how,how,how
howhowhowhow -> how,how,how,how
testhowhowhow -> how,how,how  # not clearly defined by OP

该模式是非贪婪的,因此howhowhowhow 不会映射到howhow,howhow,这也是合法的。如果您更喜欢最长匹配,请删除 ?

【讨论】:

    【解决方案2】:
    lengthofRepeatedChar = 3
    str1 = 'howhowhow'
    HowmanyTimesRepeated = int(len(str1)/lengthofRepeatedChar)
    ((str1[:lengthofRepeatedChar]+',')*HowmanyTimesRepeated)[:-1]
    'how,how,how'
    

    当你知道重复字符的长度时工作

    【讨论】:

    • 如果单词是testhowhowhow,则输出tes,tes,tes,tes
    猜你喜欢
    • 1970-01-01
    • 2018-04-10
    • 2015-05-12
    • 2013-05-18
    • 2020-01-19
    • 1970-01-01
    • 2017-07-22
    • 2020-01-07
    • 1970-01-01
    相关资源
    最近更新 更多