Python字符串 |代替()
replace()是Python编程语言中的一个内置函数,它返回字符串的副本,其中所有出现的子字符串都被另一个子字符串替换。
句法 :
string.replace(old, new, count)
参数 :
old – old substring you want to replace.
new – new substring which would replace the old substring.
count – the number of times you want to replace the old substring with the new substring. (Optional )
返回值:
它返回字符串的副本,其中所有出现的子字符串都替换为另一个子字符串。
笔记:
- 如果未指定计数,则所有出现的旧子字符串都将替换为新子字符串。
- 此方法返回字符串的副本,即它不会更改原始字符串。
下面是演示replace()的代码:
示例 1:
Python3
# Python3 program to demonstrate the
# use of replace() method
string = "geeks for geeks geeks geeks geeks"
# Prints the string by replacing all
# geeks by Geeks
print(string.replace("geeks", "Geeks"))
# Prints the string by replacing only
# 3 occurrence of Geeks
print(string.replace("geeks", "GeeksforGeeks", 3))
Python3
# Python3 program to demonstrate the
# use of replace() method
string = "geeks for geeks geeks geeks geeks"
# Prints the string by replacing
# e by a
print(string.replace("e", "a"))
# Prints the string by replacing only
# 3 occurrence of ek by a
print(string.replace("ek", "a", 3))
输出 :
Geeks for Geeks Geeks Geeks Geeks
GeeksforGeeks for GeeksforGeeks GeeksforGeeks geeks geeks
示例 2:
Python3
# Python3 program to demonstrate the
# use of replace() method
string = "geeks for geeks geeks geeks geeks"
# Prints the string by replacing
# e by a
print(string.replace("e", "a"))
# Prints the string by replacing only
# 3 occurrence of ek by a
print(string.replace("ek", "a", 3))
输出:
gaaks for gaaks gaaks gaaks gaaks
geas for geas geas geeks geeks