Reputation: 711
how do I modify the code so that it reverses the string?
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr += letter
return newStr
print(letterReverse(str))
Upvotes: 1
Views: 70
Reputation: 22564
The problem is in your line newStr += letter
. That adds the new letter to the right end of newStr
, but you want to add it to the left side. So change that line to newStr = letter + newStr
. You also should avoid using str
as a variable name, so I changed it to oldstr
. Your new code is then
oldstr = "pizza"
def letterReverse(word):
newStr = ""
for letter in word:
newStr = letter + newStr
return newStr
print(letterReverse(oldstr))
The output from that is what you want:
azzip
Upvotes: 4
Reputation: 1039
You can try this:
str = "pizza"
new_str = str[::-1]
If you want to modify your code just add [::-1] in your loop:
str = "pizza"
def letterReverse(word):
newStr = ""
for letter in word[::-1]:
newStr += letter
return newStr
print(letterReverse(str))
Upvotes: 1