Python: How exactly can you take a string, split it, reverse it and join it back together again?

Tstrmwarrior picture Tstrmwarrior · Sep 2, 2010 · Viewed 108.4k times · Source

How exactly can you take a string, split it, reverse it and join it back together again without the brackets, commas, etc. using python?

Answer

Mad Scientist picture Mad Scientist · Sep 2, 2010
>>> tmp = "a,b,cde"
>>> tmp2 = tmp.split(',')
>>> tmp2.reverse()
>>> "".join(tmp2)
'cdeba'

or simpler:

>>> tmp = "a,b,cde"
>>> ''.join(tmp.split(',')[::-1])
'cdeba'

The important parts here are the split function and the join function. To reverse the list you can use reverse(), which reverses the list in place or the slicing syntax [::-1] which returns a new, reversed list.