v3rbal
v3rbal

Reputation: 43

Moving parts of string around python

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.

Upvotes: 0

Views: 312

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174706

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'

Upvotes: 1

user2555451
user2555451

Reputation:

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'
>>>

Upvotes: 7

Related Questions