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: