在python周围移动字符串的部分

v3r*_*bal 0 python

我有一个字符串,好吧,实际上有几个.字符串很简单:

string.a.is.this
Run Code Online (Sandbox Code Playgroud)

要么

string.a.im
Run Code Online (Sandbox Code Playgroud)

以那种方式.

而我想做的是让那些叮咬成为:

this.is.a.string
Run Code Online (Sandbox Code Playgroud)

im.a.string
Run Code Online (Sandbox Code Playgroud)

我尝试过的:

new_string = string.split('.')
new_string = (new_string[3] + '.' + new_string[2] + '.' + new_string[1] + '.' + new_string[0])
Run Code Online (Sandbox Code Playgroud)

哪个适用于制作:

string.a.is.this
Run Code Online (Sandbox Code Playgroud)

this.is.a.string
Run Code Online (Sandbox Code Playgroud)

但是如果我尝试的话,会给我一个"超出范围"的错误:

string.a.im
Run Code Online (Sandbox Code Playgroud)

但如果我这样做:

new_string = (new_string[2] + '.' + new_string[1] + '.' + new_string[0])
Run Code Online (Sandbox Code Playgroud)

这工作正常:

string.a.im
Run Code Online (Sandbox Code Playgroud)

 im.a.string
Run Code Online (Sandbox Code Playgroud)

但显然不适用于:

string.a.is.this
Run Code Online (Sandbox Code Playgroud)

因为没有为4个指数设置.我试图弄清楚如何使额外的索引可选,或任何其他工作,或更好的方法.谢谢.

iCo*_*dez 7

您可以使用str.join,str.split以及[::-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'
>>>
Run Code Online (Sandbox Code Playgroud)

为了更好地解释,这是一个带有第一个字符串的逐步演示:

>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)