0

I have a string, well, several actually. The strings are simply:

string.a.is.this

or

string.a.im

in that fashion.

and what I want to do is make those stings become:

this.is.a.string

and

im.a.string

What I've tried:

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

Which works fine for making:

string.a.is.this

into

this.is.a.string

but gives me a error of 'out of range' if I try it on:

string.a.im

yet if I do:

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

that works fine to make:

string.a.im

into

 im.a.string

but obviously does not work for:

string.a.is.this

since it is not setup for 4 indices. I was trying to figure out how to make the extra index optional, or any other work around, or, better method. Thanks.

v3rbal
  • 43
  • 1
  • 11

2 Answers2

7

You can use str.join, str.split, and [::-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'
>>>

To explain better, here is a step-by-step demonstration with the first string:

>>> 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'
>>>
Community
  • 1
  • 1
  • Excellent. Clear and straight forward answer. And thanks for the extra add-on explanation, as well as the fast response, works exactly as needed. – v3rbal Jun 11 '14 at 16:47
  • You can also use reversed() instead of the slice step. e.g. '.'.join(reversed(mystr.split('.'))) – GoingTharn Jun 11 '14 at 16:49
1

You could do it through python's re module,

import re
mystr = 'string.a.is.this'
regex = re.findall(r'([^.]+)', mystr)
'.'.join(regex[::-1])
'this.is.a.string'
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274