我有一个字符串“ A,B”,由,
或分隔and
字符串可以包含多个单词,例如“ A,B,C”。它可能是3或4个字或更多。
现在我需要替换,
为or
。任何and
都不应更换。
给出示例字符串'A,B,C和D'。我的预期结果是A or B or C and D
我的尝试:
str1 = 'A,B,C and D'
str1.replace(',', ' or ')
这是正确的方法吗?
Pythonreplace()
方法将old
字符串中的(旧字符串)替换为new
(新字符串)。如果指定了第三个参数max,则替换次数不会超过max次。
str.replace(old, new[, max])
还有更多,如果您不需要替换,and
只需删除即可.replace('and','and')
。
str1 = 'A,B,C and D'
str1 = str1.replace(',',' or ').replace('and','and')
print(str1)
replace()
方法需要一个=
运算符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句