aaronbiscotti
aaronbiscotti

Reputation: 711

How do you reverse this string using a for loop

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

Answers (2)

Rory Daulton
Rory Daulton

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

Relandom
Relandom

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

Related Questions