gpt4 book ai didi

python-3.x - string.replace ,python 正在删除句子的其余部分

转载 作者:行者123 更新时间:2023-12-04 08:40:17 24 4
gpt4 key购买 nike

我试图用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 = string1.replace(name, val)
print(string1) # printing string after replace
当我执行它时:
前 :
Hello World World
后 :
Hello beautiful
预期产出:
Hello beautiful World
感谢任何

最佳答案

指定最大替换次数。

string1 = string1.replace(name, val, 1)

关于python-3.x - string.replace ,python 正在删除句子的其余部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64599250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com