Categories > Coding > Python >

reverse a string in Python

New Reply

Posts: 12

Threads: 5

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

  • Comment

Thank you

Posts: 245

Threads: 40

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.

  • 0

  • 0

  • Comment

What happens when Ε 

                                       Γ‹

                                       X

boyke

kid with a laptop

vip

Posts: 1077

Threads: 20

Joined: May, 2021

Reputation: 52

Replied

gostov you are cool for using python πŸ‘

Comments

gostov2 0 Reputation

Commented

Thanks; I'll sleep well tonight.

  • 1

  • 0

  • Comment

Posts: 1658

Threads: 80

Joined: Feb, 2020

Reputation: 87

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

gostov2 0 Reputation

Commented

i see Thank you sir for your help

  • 0

Akula 33 Reputation

Commented

summarised it nicely, saved me some time from writing it out thanks

πŸ˜‚

  • 0

  • 1

  • Comment

Whoman

#3561

Posts: 1047

Threads: 54

Joined: May, 2022

Reputation: 13

Replied

or you can just do:

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

Comments

gostov2 0 Reputation

Commented

Thank you good person

  • 0

TERIHAX 22 Reputation

Commented

yea thats hella unreadable

  • 0

Alternate 38 Reputation

Commented

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

 

also this easier

 

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

 

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

  • 0

Whoman 13 Reputation

Commented

@Alternate why you the why the why

  • 0

  • 1

  • Comment

https://i.imgur.com/21V9TOF.png

Login to unlock the reply editor

Add your reply

Users viewing this thread:

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