python 消除连续3个字符串_计算来自字符串的最大连续“a”的数量。 Python 3

Say that the user inputs:

"daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"

How would you go about finding the highest number of consecutive "a" and how would you remove the "a"'s and leave only 2 of them instead of the large number of them before.

I was thinking of appending each letter into a new empty list but i'm not sure if that's correct or what to do after.

I really don't know where to begin with this one but this is what i'm thinking:

Ask the user for input.

Create an empty list

Append each letter from the input into the list

What's next I have no idea.

second edit (something along these lines):

sentence = input("Enter your text: ")

new_sentance = " ".join(sentence.split())

length = len(new_sentance)

alist = []

while (length>0):

alist

print ()

解决方案

Starting with the input string:

input = "daslakndlaaaaajnjndibniaaafijdnfijdnsijfnsdinifaaaaaaaaaaafnnasm"

To get the max consecutive number of occurrences, you would use:

max(len(s) for s in re.findall(r'a+', input))

To replace only the longest unbroken sequence of "a"s with 2 "a"s,

you would use:

maxMatch = max(re.finditer(r'a+', input), key= lambda m: len(m.group()))

output = input[:maxMatch.start()] + "aa" + input[maxMatch.end():]

First, I obtain an iterable of MatchObjects by testing the input string against the regex a+, then use max to obtain the MatchObject with the greatest length. Then, I splice the portion of the original string up to the start of the match, the string "aa", and the portion of the original string after the end of the match to give you your final output.

To replace all occurrences of more than 2 "a"s with 2 "a"s, you

would use:

output = re.sub(r'a{3,}', "aa", input)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值