什么';我的python代码有什么问题?I';I’我试图制作一个生成器代码,用生成器替换字符串,以给出最终字符串
您没有返回递归的结果。如果没有找到匹配项,函数将返回输入什么';我的python代码有什么问题?I';I’我试图制作一个生成器代码,用生成器替换字符串,以给出最终字符串,python,Python,您没有返回递归的结果。如果没有找到匹配项,函数将返回输入字符串,否则将不返回任何内容 你想要: def make_converter(match, replacement): d={match : replacement} return d def apply_converter(converter, string): c1= "".join(str(x) for x in converter.keys()) c2= "
字符串,否则将不返回任何内容
你想要:
def make_converter(match, replacement):
d={match : replacement}
return d
def apply_converter(converter, string):
c1= "".join(str(x) for x in converter.keys())
c2= "".join(str(x) for x in converter.values())
print c1,c2
c3=string.find(c1)
if c3==-1:
return string
string=string.replace(c1,c2,1)
apply_converter(converter,string)
# For example,
c1 = make_converter('aa', 'a')
print apply_converter(c1, 'aaaa')
#>>> a
c = make_converter('aba', 'b')
print apply_converter(c, 'aaaaaabaaaaa')
#>>> ab
除了不返回结果外,我还进行了一些其他清理:
return apply_converter(converter, string)
你是说Python生成器吗?您的代码中没有任何内容。旁白:由于递归限制,如果有大量替换,此代码将中断—即使没有递归限制,如果match
是replacement
的子字符串,它将永远循环。非常感谢。成功了!:)
def make_converter(match, replacement):
return (match, replacement)
def apply_converter(converter, string):
old, new = converter
replaced = string.replace(old, new, 1)
while replaced != string:
string = replaced
replaced = string.replace(old, new, 1)
return string