[英]How to print two or more identical letter in a string?
I have a string "Hello JJ" I have to print this so that where the letters of the string that are next to each other and identical are printed on the same line. 我有一个字符串“你好JJ”我必须打印这个,以便字符串中彼此相邻且相同的字母打印在同一行上。 Like this.
像这样。
0
1 H
2 He
3 Hell
4 Hello
5 Hello
6 Hello JJ
I need to use the for loop . 我需要使用for循环 。 And the code I used this one.
我使用这个代码。
text = 'Hello.'
for position in range(0, len(text)+1):
print position, text[0:position]
But how do I make it print the identical letters at the same time (like in line 3 and 6) ? 但是如何让它同时打印相同的字母(如第3和第6行)?
text = 'Hello JJ'
counter = 0
for i in range(len(text)):
if counter:
counter -= 1
continue
for j in range(i + 1, len(text)):
if text[j] != text[i]: break
else: counter += 1
print text[0:i + counter + 1]
Output 产量
H
He
Hell
Hello
Hello
Hello JJ
>>> from itertools import groupby
>>> strs = "Hello JJ"
>>> start = ''
for k, g in groupby(enumerate(strs), key=lambda x:x[1]):
lis = list(g)
start += ''.join(x[1] for x in lis)
print lis[0][0], start
...
0 H
1 He
2 Hell
4 Hello
5 Hello
6 Hello JJ
Using itertools.groupby()
. 使用
itertools.groupby()
。
from itertools import groupby
groups = [''.join(l) for g,l in groupby("Hello JJ")]
for i in range(len(groups)+1):
print ''.join(groups[:i])
>>>
H
He
Hell
Hello
Hello
Hello JJ
split text into a list of strings. 将文本拆分为字符串列表。
import re
text = "hello piithon"
items = [m.group() for m in re.finditer(r"(.)(\1*)",s)]
for position in range(0, len(text)+1):
print position, items[0:position]
it should work. 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.