方法一:通过关键字替换
# str.replace('旧字符串' , '新字符串' , '替换最大次数(可省略)')
temp_str = '你好吗? 我很好'
# 将所有i替换成aa
print(temp_str.replace('好', '坏'))
# 将i替换成aa,只替换一次
print(temp_str.replace('好', '坏', 1))
执行结果>>>
你坏吗? 我很坏
你坏吗? 我很好
方式二:通过中括号替换
在字符串中替换自己想要的字符串。注意,要替换的字符串必须用 {} 中括号给括起来,否则无法替换
# -*- coding=utf-8 -*-
s = "{a}bc"
s=s.format(a="123")
print(s)
>>>123bc
方法三:通过下标替换
def replace_char(old_string, char, index):
"""
字符串按索引位置替换字符
old_string: 原始字符串
char: 要替换成啥?
index: 下标
"""
old_string = str(old_string)
# 新的字符串 = 旧字符串[:要替换的索引位置] + 替换成的目标字符 + 旧字符串[要替换的索引位置+1:]
new_string = old_string[:index] + char + old_string[index + 1:]
return new_string
strs = '你好吗?'
print(replace_char(strs, '我', 0))
执行结果>>>
我好吗?