目录
描述
语法和参数
返回值
使用示例
1. 省略count时
2. count值存在
注意事项
1. old_str与new_str相等时
2. count值大于old_str出现的次数
3. old_str在字符串中不存在
4. count值为0
5. count值为负
描述
Python 字符串 replace()方法是字符串替换方法,它可将字符串中的部分子串替换成新的部分,并返回新字符串。
语法和参数
str.replace(old_str, new_str, count)
名称含义备注old_str要被替换掉的子串string,不可省略的参数new_str使用new_str替换掉old_strstring,不可省略的参数count最大替换次数int,可省略的参数
返回值
string,返回替换后的新字符串。若old_str在字符串中不存在,则返回原字符串。
使用示例
1. 省略count时
当count参数省略时,在字符串中匹配到的全部old_str将会被替换成new_str:
if __name__ == '__main__':
demo = "Python: python language is fun. I love python."
print("before replace():\t", demo, id(demo))
r = demo.replace("python", "Java")
print("after replace():\t", r, id(r))
运行结果:
before replace(): Python: python language is fun. I love python. 4509860464
after replace(): Python: Java language is fun. I love Java. 4509860560
2. count值存在
如果没有省略最后的参数count,replace()方法仅将old_str替换为new_str的次数与count值相等。即replace()替换字符串的次数取决于count值的大小。
下面的例子中,我们只替换一次:
>>> demo = "西安是陕西省的著名城市,西安也是中国古代的著名都城。"
>>> result = demo.replace("西安", "咸阳", 1)
>>> result
'咸阳是陕西省的著名城市,西安也是中国古代的著名都城。'
>>> id(demo)
4366833712
>>> id(result)
4366833840
注意事项
1. old_str与new_str相等时
当要新替换的字符串与旧字符串相等时,replace()方法不会报错。此时如果new_str将old_str全部替换完,replace()方法返回原字符串。
>>> demo = "banana, apple, orange"
>>> result = demo.replace("apple", "apple")
>>> result
'banana, apple, orange'
>>> id(demo)
4367589288
>>> id(result)
4367589288
2. count值大于old_str出现的次数
当count值大于old_str出现的次数时,replace()方法不会报错,此时count参数出现没有任何意义:
>>> demo = "go.micro.compute"
>>> result = demo.replace("go", "python", 100)
>>> result
'python.micro.compute'
3. old_str在字符串中不存在
当old_str在原字符串中不存在时,使用replace()方法不会报错,并返回原字符串:
if __name__ == '__main__':
place = "caf\u00e9"
result = place.replace("e", "~")
print("place", place)
print("result", result)
print("place id", id(place))
print("result id", id(result))
运行结果:
place café
result café
place id 4553216048
result id 4553216048
4. count值为0
count值为0,replace()不会做任何操作,返回原字符串。
if __name__ == '__main__':
action = "I like having coffee at starbucks"
result = action.replace("coffee", "water", 0)
print("action", action)
print("result", result)
print("action id:", id(action))
print("result id:", id(result))
运行结果:
action I like having coffee at starbucks
result I like having coffee at starbucks
action id: 4513124264
result id: 4513124264
5. count值为负
当count值为负,replace()方法将全部old_str替换为new_str。这种场景下count参数作用失效:
if __name__ == '__main__':
action = "a a a b c"
result = action.replace("a", "d", -1)
print("action", action)
print("result", result)
print("action id:", id(action))
print("result id:", id(result))
运行结果:
action a a a b c
result d d d b c
action id: 4318863024
result id: 4319003120