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

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


>>> 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.


Do you mean like this?

import stringastr='a(b[c])d'deleter=string.maketrans('()[]','    ')print(astr.translate(deleter))# a b c  dprint(astr.translate(deleter).split())# ['a', 'b', 'c', 'd']print(list(reversed(astr.translate(deleter).split())))# ['d', 'c', 'b', 'a']print(' '.join(reversed(astr.translate(deleter).split())))# d c b a


Not fitting 100% to this particular question but if you want to split from the back you can do it like this:

theStringInQuestion[::-1].split('/', 1)[1][::-1]

This code splits once at symbol '/' from behind.