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'
>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))