How is it possible to convert in elegant way strings like:
\'test.test1.test2\'
\'test.test3.test4\'
into strings like these:
No need for regular expressions here.
Use str.rsplit():
output = inputstr.rsplit('.', 1)[0]
or str.rpartition():
output = inputstr.rpartition('.')[0]
str.rpartition()
is the faster of the two but you need Python 2.5 or newer for it.
Demo:
>>> 'test.test1.test2'.rsplit('.', 1)[0]
'test.test1'
>>> 'test.test1.test2'.rpartition('.')[0]
'test.test1'
>>> 'test.test3.test4'.rsplit('.', 1)[0]
'test.test3'
>>> 'test.test3.test4'.rpartition('.')[0]
'test.test3'
And a time comparison against a million runs:
>>> from timeit import timeit
>>> timeit("s.rsplit('.', 1)[0]", "s = 'test.test1.test2'")
0.5848979949951172
>>> timeit("s.rpartition('.')[0]", "s = 'test.test1.test2'")
0.27417516708374023
where you can run 2 million str.rpartition()
calls for the price of 1 million str.rsplit()
's.
Use rsplit to split from the end, limit to 1 split:
your_string.rsplit('.', 1)