Reputation: 151
I want to reverse the string using the Loop & Function. But when I use the following code, it is output the exact same string again. But it suppose to reverse the string. I can't figure out why.
def reversed_word(word):
x=''
for i in range(len(word)):
x+=word[i-len(word)]
print(i-len(word))
return x
a=reversed_word('APPLE')
print(a)
Upvotes: 0
Views: 368
Reputation: 882028
If you look at the output of your debug statement (the print
in the function), you'll see you're using the indexes -5
through -1
.
Since negative indexes specify the distance from the end of the string, -5
is the A
, -4 is the first P
, and so on. And, since you're appending these in turn to an originally empty string, you're just adding the letters in the same order they appear in the original.
To add them in the other order, you can simply use len(word) - i - 1
as the index, giving the sequence (len-1) .. 0
(rather than -len .. -1
, which equates to 0 .. (len-1)
):
def reversed_word(word):
result = ""
for i in range(len(word)):
result += word[len(word) - i - 1]
return result
Another alternative is to realise you don't need to use an index at all since iterating over a string gives it to you one character at a time. However, since it gives you those characters in order, you need to adjust how you build the reversed string, by prefixing each character rather than appending:
def reverse_string(word):
result = ""
for char in word:
result = char + result
return result
This builds up the reversed string (from APPLE
) as A
, PA
, PPA
, LPPA
and ELPPA
.
Of course, you could also go fully Pythonic:
def reverse_string(word):
return "".join([word[i] for i in range(len(word), -1, -1)])
This uses list comprehension to create a list of characters in the original string (in reverse order) then just joins that list into a single string (with an empty separator).
Probably not something I'd hand in for classwork (unless I wanted to annoy the marker) but you should be aware that that's how professional Pythonistas usually tackle the problem.
Upvotes: 2
Reputation: 14434
Let's say your word is python
.
You loop will then iterate over the values 0
through 5
, since len(word) == 6
.
When i
is 0
, i-len(word)
is -6
(note carefully that this value is negative). You'll note that word[-6]
is the character six places to the left from the end of the string, which is p
.
Similarly, when i
is 1
, i-len(word)
is -5
, and word[i-len(word)]
is y
.
This pattern continues for each iteration of your loop.
It looks like you intend to use positive indices to step backward through the string with each iteration. To obtain this behavior, try using the expression len(word)-i-1
to index your string.
Upvotes: 1
Reputation: 147
def reversed_word(word):
reversed = ''
for i in range(len(word)-1, -1, -1):
reversed += word[i]
return reversed
print(reversed_word("apple"))
Upvotes: 0