2014-06-11 6 views
0

저는 실제로 문자열을 가지고 있습니다. 문자열은 단순히 :파이썬을 중심으로 한 문자열의 이동 부분

string.a.is.this 

또는 패션

string.a.im 

.

this.is.a.string 

im.a.string 

내가 무엇을 시도했다 : 만들기 위해 잘 작동

new_string = string.split('.') 
new_string = (new_string[3] + '.' + new_string[2] + '.' + new_string[1] + '.' + new_string[0]) 

는 무엇을 할 원하는 그 침이 되십시오입니다 :

string.a.is.this 
내가 할 경우 아직

string.a.im 

:

this.is.a.string 

하지만 나에게의 오류를 제공은 '범위 초과'나는 그것을하려고하면 잘 작동하는

new_string = (new_string[2] + '.' + new_string[1] + '.' + new_string[0]) 

하기 :

string.a.im 
이 4 개 인덱스에 대한 설정이되지 않기 때문에

string.a.is.this 

: 분명히

im.a.string 

만에 16,

은 작동하지 않습니다. 여분의 인덱스를 선택적으로 만드는 방법을 알아 내려고 했었습니다. 감사.

답변

7

당신은 str.join, str.split[::-1] 사용할 수 있습니다

>>> mystr = 'string.a.is.this' 
>>> 
>>> # Split the string on . 
>>> mystr.split('.') 
['string', 'a', 'is', 'this'] 
>>> 
>>> # Reverse the list returned above 
>>> mystr.split('.')[::-1] 
['this', 'is', 'a', 'string'] 
>>> 
>>> # Join the strings in the reversed list, separating them by . 
>>> '.'.join(mystr.split('.')[::-1]) 
'this.is.a.string' 
>>> 
+0

Excelle nt. 명확하고 직선적 인 대답. 추가 기능에 대한 설명과 빠른 응답 덕분에 필요에 따라 정확하게 작동합니다. – v3rbal

+0

슬라이스 단계 대신 역상()을 사용할 수도 있습니다. 예 : '.'가입 (반전 (mystr.split ('.'))) – GoingTharn

+0

@GoingTharn도 훌륭한 대답입니다. 감사합니다 – v3rbal

1

당신은 그것을 할 수 :

>>> mystr = 'string.a.is.this' 
>>> '.'.join(mystr.split('.')[::-1]) 
'this.is.a.string' 
>>> mystr = 'string.a.im' 
>>> '.'.join(mystr.split('.')[::-1]) 
'im.a.string' 
>>> 

더 잘 설명하기 위해, 여기에 첫 번째 문자열과 단계별 데모입니다 Python의 모듈을 통해

import re 
mystr = 'string.a.is.this' 
regex = re.findall(r'([^.]+)', mystr) 
'.'.join(regex[::-1]) 
'this.is.a.string' 
관련 문제