我该如何修改代码以使其反转字符串?
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr += letter
return newStr
print(letterReverse(str))
答案 0 :(得分:4)
问题出在您的newStr += letter
行中。这样会将新字母添加到newStr
的右端,但是您想将其添加到左侧。因此,将该行更改为newStr = letter + newStr
。您还应该避免将str
用作变量名,因此我将其更改为oldstr
。那么您的新代码就是
oldstr = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr = letter + newStr
return newStr
print(letterReverse(oldstr))
从中得到的输出就是您想要的:
azzip
答案 1 :(得分:1)
您可以尝试以下方法:
str = "pizza"
new_str = str[::-1]
如果要修改代码,只需在循环中添加[::-1]:
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word[::-1]:
newStr += letter
return newStr
print(letterReverse(str))