Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么某些字符串中会跳过重复的字母?_Python_For Loop_Indexing - Fatal编程技术网

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

Python 为什么某些字符串中会跳过重复的字母?,python,for-loop,indexing,Python,For Loop,Indexing,此代码旨在“分解”给定字符串 def string_splosions(s): """erp9yoiruyfoduifgyoweruyfgouiweryg""" new = '' for i in s: new += s[0:int(s.index(i))+1] return new 出于某种原因,此代码可以为大多数单词返回正确的“爆炸”,但是有重复字母的单词打印不正确。 例子 正确的输出是: 代码->CCoCodCode abc->aababc

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

def string_splosions(s):
    """erp9yoiruyfoduifgyoweruyfgouiweryg"""
    new = ''
    for i in s:
        new += s[0:int(s.index(i))+1]
    return new
出于某种原因,此代码可以为大多数单词返回正确的“爆炸”,但是有重复字母的单词打印不正确。 例子

正确的输出是:

代码->CCoCodCode abc->aababc 馅饼->馅饼 输入s时输出不正确 Hello->hhehellHello应该是hhehellHello
注意:在不正确的输出中,从第二次到最后一次的重复中应该还有1个l。

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

def string_splosion(s):
    new = ''
    for i in s:
        new += s[0:int(s.index(i))+1]
    return new
问题是indexi返回该字符的第一个实例的索引,对于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)))

提问时请不要在堆栈溢出上发布图片,而是在问题中发布正确格式的实际代码。返回:返回找到子字符串sub的s中的最低索引。因此,每次在aaa中搜索a时,它都会找到第一个。递归:返回字符串\u splosions[:-1]+s如果lens>1,则返回其他s: