What is the most efficient way to spell a string in reverse, for instance s = "banana".

Recommended Answers

All 3 Replies

Member Avatar for Mouche

This works:

s = "banana"
s_reversed = s[::-1]

It might be helpful to encapsulate it:

def s_reverse(s):
    return s[::-1]

s = "banana"
s_reversed = s_reverse(s)
print s_reversed # ananab

x = "hello"
x_r = s_reverse(x)
print x_r # olleh

Works great! I have to play around with Python slicing. Thanks LaMouche!

Member Avatar for Mouche

No problem. I must say that wasn't my original code. I used the mighty google. ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.