为什么在某些字符串中跳过重复的字母?

时间:2018-06-06 23:15:20

标签: python for-loop indexing

此代码旨在“爆炸”给定的字符串s

def string_splosions(s):
    """erp9yoiruyfoduifgyoweruyfgouiweryg"""
    new = ''
    for i in s:
        new += s[0:int(s.index(i))+1]
    return new

由于某些原因,此代码可以为大多数单词返回正确的“爆炸”,但是具有重复字母的单词却无法正确打印。 实例

正确的输出是:

Code --> CCoCodCode

abc  --> aababc

pie  --> ppipie

incorrect outputs when s is

Hello --> HHeHelHelHello (should be HHeHelHellHello)

(注意:在错误的输出中,第二次到最后一次重复应该有1个l。)

1 个答案:

答案 0 :(得分:3)

您应该转录代码而不是发布图片:

def string_splosion(s):
    new = ''
    for i in s:
        new += s[0:int(s.index(i))+1]
    return new

问题是索引(i)返回该字符的第一个实例的索引,对于" Hello"中的两个l都是2。解决方法是直接使用索引,这也更简单:

def string_splosion(s):
    new = ''
    for i in range(len(s)):
        new += s[:i+1]
    return new

甚至:

def string_splosion(s):
    return ''.join(s[:i+1] for i in range(len(s)))
相关问题