Categories > Coding > Python >

reverse a string in Python

Posts: 13

Threads: 8

Joined: Mar, 2023

Reputation: 0

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?

  • 0

Thank you

yvneEnvy

<><><<>>><<>

Posts: 303

Threads: 47

Joined: Mar, 2023

Reputation: 3

Replied

Thanks for the lesson, vouch.

Comments

gostov2 0 Reputation

Commented

You're welcome, compinche

  • 0

yvneEnvy 3 Reputation

Commented

Look at me hector, look at me.

  • 1

  • 0

Posts: 1391

Threads: 71

Joined: May, 2022

Reputation: 17

Replied

or you can just do:

def reverse(x):
    return x[::-1]

Comments

gostov2 0 Reputation

Commented

Thank you good person

  • 0

TERIHAX 30 Reputation

Commented

yea thats hella unreadable

  • 0

Alternate 36 Reputation

Commented

@TERIHAX no it not just need be pro 😎😎😎😎😎😎

 

also this easier

 

reverse = lambda x: x[::-1]

 

easy pro frfr ong πŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ—ΏπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ‡ΊπŸ‡ΈπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸžπŸ˜ŽπŸ˜ŽπŸ˜ŽπŸ˜Ž

  • 0

Whoman 17 Reputation

Commented

@Alternate why you the why the why

  • 0

TERIHAX 30 Reputation

Commented

@Alternate omg really???

  • 0

  • 1

Did I mention I use arch btw?

zenkai

zenkai

Posts: 5

Threads: 0

Joined: Apr, 2023

Reputation: 0

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:

  1. output = "" + "H" = "H"
  2. output = "H" + "e" = "eH"
  3. output = "eH" + "l" = "leH"
  4. output = "leH" + "o" = "oleH"

Finally, the reversed string "oleH" is returned and printed as the output. πŸ‘

  • 0

https://cdn.discordapp.com/attachments/1113823000429600880/1114600004032663552/User.gif?width=1000&height=100

Users viewing this thread:

( Members: 0, Guests: 1, Total: 1 )