Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to add string prefix if prefix absent

In Python3 I have 3 strings:

string1 = '[Foo] bar1'
string2 = '[foo] bar2'
string3 = 'bar3'

I would like to add prefix "Foo" for each string, except first string that already have it. And replace lower "f" to upper "F" in string2.
So, I mean, that result must be:

'[Foo] bar1' -> nothing to do
'[foo] bar2' -> '[Foo] bar2'
'bar3' -> '[Foo] bar3'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use startswith to check if the prefix is there (case insensitive; no regex needed). If so, remove it. In all cases, add the prefix (again), but in its proper capitalisation.

def prefixwith(s, prefix):
    if s.upper().startswith(prefix.upper()):
        s = s[len(prefix):].lstrip()  # Remove existing prefix
    return prefix + ' ' + s

Call as follows:

prefix = '[Foo]'
print(prefixwith('[Foo] bar1', prefix))
print(prefixwith('[foo] bar2', prefix))
print(prefixwith('bar3', prefix))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading