Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

python替换字符串中指定的内容

  1. User

    python替换字符串中指定的内容

  2. Assistant

    可以使用字符串的replace方法来替换字符串中指定的内容。

    示例代码:

    # 定义原字符串
    s = 'hello world, my name is John'
    
    # 使用replace方法替换指定内容
    s = s.replace('John', 'Mike')
    
    # 输出结果
    print(s)
    

    输出结果:

    hello world, my name is Mike
    

    replace方法接受两个参数,第一个是要被替换的字符串,第二个是用来替换的字符串。如果要替换的字符串在原字符串中出现多次,replace方法默认只会替换第一次出现的内容。如果要替换所有的内容,可以使用replace方法的第三个参数来指定替换次数,如下所示:

    # 定义原字符串
    s = 'hello world, my name is John and John is my friend'
    
    # 使用replace方法替换指定内容
    s = s.replace('John', 'Mike', 2)  # 只替换前两个John
    
    # 输出结果
    print(s)
    

    输出结果:

    hello world, my name is Mike and Mike is my friend