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
Replied
or you can just do:
def reverse(x):
return x[::-1]
Comments
gostov2 0 Reputation
Commented
Thank you good person
TERIHAX 30 Reputation
Commented
yea thats hella unreadable
Whoman 17 Reputation
Commented
@Alternate why you the why the why
TERIHAX 30 Reputation
Commented
@Alternate omg really???
Cancel
Post
Did I mention I use arch btw?
Replied
In the given code, the reverse
function takes a string x
as input and returns the reversed version of that string.
The loop iterates through each character c
in the input string. In each iteration, the current character c
is concatenated with the existing output
string using the c + output
operation. By using this operation, the current character is added at the beginning of the output
string, effectively reversing the order of characters.
So, when you call reverse("Helo")
, the iterations will proceed as follows:
output = "" + "H" = "H"
output = "H" + "e" = "eH"
output = "eH" + "l" = "leH"
output = "leH" + "o" = "oleH"
Finally, the reversed string "oleH" is returned and printed as the output. π
Cancel
Post
https://cdn.discordapp.com/attachments/1113823000429600880/1114600004032663552/User.gif?width=1000&height=100
Users viewing this thread:
( Members: 0, Guests: 2, Total: 2 )
Comments
gostov2 0 Reputation
Commented
You're welcome, compinche
0
yvneEnvy 3 Reputation
Commented
Look at me hector, look at me.
1