Sunday, February 10, 2008

reverse a string in Python

How to reverse a string?

s = 'abc'
s = s[::-1]
print s


Simple! :-)

26 comments:

Hans said...

Yeah, but it might be useful to explain to newbies what the slice notation does. If I were new to Python, then "s[::-1]" would look positively odd to me... I certainly would not think it reverses the string. Just a thought. :-)

--Hans

subeen said...

Thanks for your comment. I didn't explain it as I thought it would be fun for anyone who tries to think how s[::-1] works :)

priyeshsolanki said...

i appreciate.
it really helpful.
thanks.

teci said...

Simple yet so useful! Thanks :)

Bhavin Patel said...

explain how it works ?

or any link for explanation will be helpful.

thanks.

Juho Vepsäläinen said...

Bhavin Patel: "::" is known as stride notation.

Example:
>>> foo = [2, 5, 1, 8]

Regular slice (returns all)
>>> foo[:]
[2, 5, 1, 8]

Slice with stride (returns every nth)
>>> foo[::2]
[2, 1]

Stride works inversely as well
>>> foo[::-2]
[8, 5]

Hence it can be used to reverse a string (stride backwards using step length of one)
>>> 'foobar'[::-1]
'raboof'

There is another way to reverse as well. This can be done using "reversed" generator:
>>> ''.join([char for char in reversed('foobar')])
'raboof'

As the list comprehension returns a list I had to join it separately. Normally the [::-1] trick should work just fine. "reversed" may be useful in some special cases, however.

Check out http://www.python.org/doc/2.3.5/whatsnew/section-slices.html for more comprehensive documentation.

Praveen Kumar said...

Thank you very much its simple and nice

krishna said...

It's very nice... yare

saikat said...

s = 'abc'

s = s[::2]

print s


#for this code it returns ac
#how

theburkdefender said...

it should be "ca", isn't it?

KG said...

thanks it is very helpful and explained very well

Does anyone know what i should use to extract string/substring from a string?

praveen said...

That really proves the power of python, for which it would take couple of lines in other languages.

glykocalyx said...

Python is really a nice language. Just for comparison, that is how i would do it in perl:

print $string = reverse("ABC")

Rajeev S said...

thanks......workz perfectly as i expected

Sumit Bhagwani said...

Awesome thing!!

sambhav said...

>>>s='spam'
>>>print s[:]
spam
>>>print s[::-1]
maps
>>>print s[0:len(s)]
spam
>>>print s[0:len(s):-1]
(prints nothing)

Any reason, why ??

Red_Devil said...

@saikat

s='abc'
print s[::-2]

returns 'ca' only...

casper said...

i'm new to python, i need a program to convert any decimal number in to octal(base 8):using python 2.7 ,can any one give me an idea how to write it :please help me~!

Nat said...

@casper

You could do this:
oct(12)

that would return
'014' as a string

To enter an octal number literal, precede with a 0:
0122 will return 82 in base 10

to go from an octal string to an int:
int('014',8)

Nat said...
This comment has been removed by the author.
aJ said...
This comment has been removed by the author.
aJ said...

You can also use this technique to reverse words in a sentence:

>>> sentence = "one two three four"
>>> ' '.join( [ word[::-1] for word in sentence.split() ] )[::-1]
'four three two one'

J.Naveen said...

The above example is simplified as

>>> sentence = "one two three four"
>>> ' '.join( [ word for word in sentence.split() ] [::-1])
'four three two one'

Smileman said...

but when I tried it, it doesn't print the space between the reversed i.e the output is like this fourthreetwoone

the_derp said...

Hmm, i did it but here's what I thought regarding this.
[::-1]

[:] <-- this gets all of the string

while [::(value)] skips or reverse the string. if it is negative, the skipping starts from the last character of the string depends on the number.

for example, you can put -2 instead of -1.

s = 'abcdef'
s = s[::-2]
print s

if counted base on the slice number, it would creat a group of three which are fe, dc and ba. the first character of each group (f,d,b) will appended to formed a value and stored it to the variable 's'.

Modelagem Matematico Computacional said...

maybe the easiest way is


revword = ''

for letter in reversed(word): revword += letter

print revword