Python 3.x string.replace,python正在删除句子的其余部分
我试图用python3中的beautiful替换第一世界,但它并没有像我预期的那样工作: 我的代码:Python 3.x string.replace,python正在删除句子的其余部分,python-3.x,Python 3.x,我试图用python3中的beautiful替换第一世界,但它并没有像我预期的那样工作: 我的代码: string1 = 'Hello World World' # Define my string name = 'World' # word to replace val = 'beautiful' # word remplacing the word to replace print(string1) # printing string before replace string1 = str
string1 = 'Hello World World' # Define my string
name = 'World' # word to replace
val = 'beautiful' # word remplacing the word to replace
print(string1) # printing string before replace
string1 = string1.replace(name, val)
print(string1) # printing string after replace
当我执行它时:
之前:
Hello World World
之后:
Hello beautiful
预期产出:
Hello beautiful World
感谢您提供的任何请指定最大替换次数
string1 = string1.replace(name, val, 1)