简体   繁体   English

如何在字符串中打印两个或多个相同的字母?

[英]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.

相关问题 如何使两个或多个特定字母组合? - how to make two or more combinations of specific letter? 如何通过在python中逐个字母和反向打印来打印字符串 - How to print a string by printing letter by letter and in reverse in python 如何打印不包含特定字母字符串的单词? - how to print words excluding particular letter string? 如何仅将字符串中的每个字母打印一次 - How to print each letter in a string only once 如何打印用户想要的某个字符串的字母 - How to print the letter of a certain string that the user wants 如何在列表中打印两个相同项目的索引值? - How to print the index values of two identical items in a list? 如何检查列表中是否存在超过3个相同的字符串,Python - How to check if there are more than 3 identical string in a list, Python 如何询问字符串,然后询问字符串的位置,然后删除字母并打印没有字母的单词 - How to ask for a string, then ask for a position of string, then remove the letter and print the word without the letter 在打印字符串中打印希腊字母 - Print Greek letter in printed string 如何用大写和小写字母打印每个 8 个字母的字符串? (在蟒蛇中) - How to print every 8-letter string with uppercase and lowercase letters? (In python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM