我正在尝试创建一个程序,用不同的字符或一段文字替换某些字符或一组字符。
我到目前为止所拥有的是
def changeWords(sentence):
for char in sentence:
if char == 'a':
printSameLine('x')
elif char == 'bd':
printSameLine('y')
else:
printSameLine(char)
def goWordChange():
print('')
print('paste text to change')
print('')
text = input()
print('')
changeWords(text)
print('')
return goWordChange()
goWordChange()
如果输入,请输入“ abcd acbd”
输出将是
xbcd xcbd
但我希望它成为
xbcd xcy
我不太确定为什么可以代替“ a”而不是“ bc”。我怎样才能改变一个以上的角色?
(ps。我仍然是编程的初学者,所以请使用小写字母:))
您的代码无法处理替换多个字符的子字符串的原因是因为您的循环一次for char in sentence:
循环一个字符。要查看此内容print(char)
,请在代码中的该循环之后立即进行调用,看看是否char
等于'bd'
。
python中的方便字符串具有一种称为的方法replace
,该方法返回新字符串,将所有出现的旧子字符串替换为新字符串。这使您不必担心循环遍历字符或成对的字符或其他任何内容(尽管尝试不花replace
时间解决问题可能是一个很好的练习)。这是python解释器中的示例:
>>> string = "Hello World!"
>>> new_string = string.replace("o", "a")
>>> print(string)
Hello World!
>>> print(new_string)
Hella Warld!
>>> print(string.replace("Hello", "Goodbye"))
Goodbye World!
值得强调的是,replace
它不会更改初始字符串,它只会返回更改后的新字符串。
这可能适合您的程序:
def changeWords(sentence):
temp_sentence = sentence.replace("a","x")
temp_sentence = temp_sentence.replace("bd", "y")
return temp_sentence
或更紧凑地说,您可以执行以下操作:
def changeWords(sentence):
return sentence.replace("a","x").replace("bd", "y")
然后,您需要更改goWordChange
为以下内容:
def goWordChange():
print('')
print('paste text to change')
print('')
text = input()
print('')
new_text=changeWords(text)
print('')
print(new_text)
return goWordChange()
goWordChange
在这种情况下,顺便说一句具有递归性(在结尾处调用自身)有点难看。我会摆脱那条线,goWordChange
而在像这样的无限循环中被调用:
while True:
goWordChange()
由于这种形式使事情变得更加明显,因此可能具有更好的性能(并且python限制了递归深度)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句