Categories > Coding > Python >
reverse a string in Python
Posted
First have a look at the code:
def reverse(x):
output = ""
for c in x:
output = c + output
return output
print(reverse("Helo"))
This function works great in Python to invert a text; I just don't understand why or how it works.
If I iterate through a string, for example, it will usually start at "H" and work its way down to "O." How come it's going backwards here?
Cancel
Post
Thank you
Replied
Thanks for the lesson, vouch.
Cancel
Post
What happens when Ε
Γ
X
Replied
gostov you are cool for using python π
Comments
gostov2 0 Reputation
Commented
Thanks; I'll sleep well tonight.
Cancel
Post
https://i.imgur.com/fqGoInR.png
fortnite balls
Replied
It's because you're doing c + output instead of output + c. The character is put first, then the rest, so it's building it in a reverse order. If you're reversing "hello" with this function, your output will look like this per iteration: "", "h", "eh", "leh", "lleh", "olleh".
Comments
Cancel
Post
Replied
or you can just do:
def reverse(x):
return x[::-1]
Comments
gostov2 0 Reputation
Commented
Thank you good person
TERIHAX 22 Reputation
Commented
yea thats hella unreadable
Whoman 13 Reputation
Commented
@Alternate why you the why the why
Cancel
Post
https://i.imgur.com/21V9TOF.png
Users viewing this thread:
( Members: 0, Guests: 1, Total: 1 )
Comments
gostov2 0 Reputation
Commented
You're welcome, compinche
0
yvneEnvy 3 Reputation
Commented
Look at me hector, look at me.
0