2010-09-02 8 views

Odpowiedz

44
>>> tmp = "a,b,cde" 
>>> tmp2 = tmp.split(',') 
>>> tmp2.reverse() 
>>> "".join(tmp2) 
'cdeba' 

lub prościej:

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

ważne części tutaj są split function i join function. Aby odwrócić listę, można użyć reverse(), która odwraca listę w miejscu lub składnia podziału [::-1], która zwraca nową, odwróconą listę.

+5

Alternatywnie, ''' .join (odwrócone (tmp.split (',')))', które jest trochę bardziej wyraźne. – carl

2

Masz na myśli?

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 
0

Masz na myśli to?

from string import punctuation, digits 

takeout = punctuation + digits 

turnthis = "(fjskl) 234 = -345 089 abcdef" 
turnthis = turnthis.translate(None, takeout)[::-1] 
print turnthis 
Powiązane problemy