How is it possible to convert in elegant way strings like:
'test.test1.test2'
'test.test3.test4'
into strings like these:
'test.test1'
'test.test3'
substring() The easiest way is to use the built-in substring() method of the String class. In order to remove the last character of a given String, we have to use two parameters: 0 as the starting index, and the index of the penultimate character.
In Python you can use the replace() and translate() methods to specify which characters you want to remove from a string and return a new modified string result. It is important to remember that the original string will not be altered because strings are immutable.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With