在 Python 中,字符串替换函数 replace 用于将字符串中指定的一部分替换为另一个字符串。
replace(old, new, count=None)
>>> my_string = "123-456-7890" >>> my_string.replace(r"\d", "") '--'在此示例中,正则表达式 r"\d" 匹配所有数字字符,并将它们替换为 。
>>> my_string = "Hello, Python, Python!" >>> my_string.replace("Python", "Java", 1) 'Hello, Java, Python!'在此示例中,count 参数设置为 1,因此仅第一个匹配的 Python 子字符串被替换为 Java。
>>> my_string = "Hello, world! My name is John." >>> my_string.replace("world|John", "Python|Jane") 'Hello, Python! My name is Jane.'在此示例中,管道符号将 world 和 John 分隔为两个独立的子字符串,并用 Python 和 Jane 替换它们。
本文地址:https://www.qianwe.com/article/a6ccb05522c77dc58072.html