How exactly can you take a string, split it, reverse it and join it back together again without the brackets, commas, etc. using python?
views:
105answers:
3
+6
A:
>>> 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.
Fabian
2010-09-02 13:00:55
Alternatively, `''.join(reversed(tmp.split(',')))`, which is a little more explicit.
carl
2010-09-02 16:49:21
+2
A:
Do you mean like this?
import string
astr='a(b[c])d'
deleter=string.maketrans('()[]',' ')
print(astr.translate(deleter))
# a b c d
print(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
unutbu
2010-09-02 13:04:27
A:
You mean this?
from string import punctuation, digits
takeout = punctuation + digits
turnthis = "(fjskl) 234 = -345 089 abcdef"
turnthis = turnthis.translate(None, takeout)[::-1]
print turnthis
Tony Veijalainen
2010-09-02 13:06:46