Ad

Python3: Remove A Substring Between Two Delimiting Char

- 1 answer

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

Ad

Answer

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'
Ad
source: stackoverflow.com
Ad