为什么有些字符串中会跳过重复的字母?

2024-09-30 22:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码旨在“分解”给定的字符串

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

由于某些原因,此代码可以为大多数单词返回正确的“explosion”,但是有重复字母的单词不能正确打印。 举例说明。你知道吗

正确的输出是:

Code --> CCoCodCode

abc  --> aababc

pie  --> ppipie

incorrect outputs when s is

Hello --> HHeHelHelHello (should be HHeHelHellHello)

(注意:在不正确的输出中,从第二次到最后一次的重复中应该还有1个l。)


Tags: 字符串代码innewforstringindexreturn
1条回答
网友
1楼 · 发布于 2024-09-30 22:25:13

您应该转录代码,而不是张贴图片:

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)))

相关问题 更多 >