Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the last part of string separated with dot in Python

Tags:

python

regex

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'
like image 963
Konstantin Avatar asked Mar 02 '14 09:03

Konstantin


People also ask

How do I remove the last dot from a string in Python?

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.

How do you remove certain parts of a string in Python?

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.


2 Answers

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.

like image 196
Martijn Pieters Avatar answered Oct 01 '22 11:10

Martijn Pieters


Use rsplit to split from the end, limit to 1 split:

your_string.rsplit('.', 1)
like image 33
Nicolas Defranoux Avatar answered Oct 01 '22 11:10

Nicolas Defranoux