user6882757
user6882757

Reputation:

How to add new string between a string python

I have a string 'A,B' which is separated by , or and

The String could have several words like 'A,B,C'. It may be 3 or 4 words and more.

Now I need to replace , with or. Any and should not be replaced.

Give an example string 'A,B,C and D' . My expected result is A or B or C and D

My attempt:

str1 = 'A,B,C and D' 
str1.replace(',', ' or ')

Is this the correct method?

Upvotes: 0

Views: 79

Answers (1)

dyy.alex
dyy.alex

Reputation: 534

The Python replace() method replaces the old (old string) in the string with new (new string). If the third parameter max is specified, the replacement will not exceed max times.

str.replace(old, new[, max])

And more, if you do not need to replace and just delete .replace('and','and').

str1 = 'A,B,C and D' 
str1 = str1.replace(',',' or ').replace('and','and')
print(str1)

replace() method need a = operator.

Upvotes: 1

Related Questions