Marcel Sonderegger
Marcel Sonderegger

Reputation: 820

Python3: remove a substring between two delimiting char

I am looking for a clean solution in Python3 to cut a substring out of a string (like an inline comment). However,if it is an odd number of seperators, then the rest of the text shall be removed (like a remark at the end of a programming line)

input:

s="abcd;efghij;kl;mn"

output:

s="abcdkl"

How can this be done in a similar way like .replaceAll in Java

Upvotes: 1

Views: 5523

Answers (3)

Kasravnd
Kasravnd

Reputation: 107297

If you only have two separator you can use str.split() as following:

In [15]: sp = s.split(';')

In [18]: result = sp[0] + sp[-1]

In [19]: result
Out[19]: 'abcdklmn'

Otherwise, based on your string and expected result you can use regular expressions to find the desired sub-strings.

Demo:

In [25]: s
Out[25]: 'abcd;efghij;klmn'

In [26]: re.sub(r'(;[^;]*)?;', '', s)
Out[26]: 'abcdklmn'

In [27]: s="abcd;klmn"

In [28]: re.sub(r'(;[^;]*)?;', '', s)
Out[28]: 'abcdklmn'

Upvotes: 1

hygull
hygull

Reputation: 8740

@Marcel, as you are satisfied with the above approach suggested by @Kasramvd, it is good and I want to suggest you to write a simple tiny function using lambda keyword.

Call it multiple times with new parameters and get the output as the below code shows.

Visit and check https://www.python-course.eu/lambda.php for detailed examples.

See Python lambda function for brief knowledge.

>>> get_string = lambda s: s.split(';')[0] + s.split(';')[-1]
>>>
>>> get_string("abcd;efghij;klmn")
'abcdklmn'
>>>
>>> get_string("ABCD;MONKEY;XYZ")
'ABCDXYZ'
>>>
>>> get_string("PYTHON;abcd;LEARN")
'PYTHONLEARN'
>>>

Upvotes: 4

Anatolii
Anatolii

Reputation: 14660

You could do it using a regexp:

import re
delimiters = ';'
s = 'fsdfsd;sfdsfd;ffs'
reg_exp = "[" + delimiters + "].*[" + delimiters + "]"
new_s = re.sub(reg_exp, "", s)
print (new_s)

Upvotes: 1

Related Questions