Python字符串替换方法,你知道怎样操作吗?4分钟带你了解
字符串替换
4 分钟阅读
在 中替换字符串的一种简单而强大的方法是使用 字符串 () 方法。
是最好的脚本语言之一,它最容易与 集成以实现基于 Web 的自动化,这需要大量的字符串处理。可能需要使用字符串处理来构建动态 XPat...
字符串替换
4 分钟阅读
在 中替换字符串的一种简单而强大的方法是使用 字符串 () 方法。
是最好的脚本语言之一,它最容易与 集成以实现基于 Web 的自动化,这需要大量的字符串处理。可能需要使用字符串处理来构建动态 XPath、比较日期和搜索子字符串。因此使用 字符串 () 方法是不可避免的。
在 中替换字符串

用示例定义 字符串替换方法
如何在 中替换字符串
通常,您将在 中处理字符串,通过用另一部分文本替换一部分来修改其内容。(str )
在中一切都是一个对象,对于字符串也是如此。这意味着这是一个字符串对象。 的字符串模块提供了一个 () 方法
1-调用 ()
() 方法签名
方法具有以下语法。
str.replace(s, old, new[, replacefreq])
下面是传递给该方法的参数的摘要。
中的字符串替换示例
示例 1:使用模块名称调用 ()
oldString = 'I love Python 2.0'
import string
newString = string.replace(oldString, '2.0', '3.0')
print(newString)
newString = string.replace(oldString, '2.0', '3.0.')
print(newString)
oldString = 'Are you a tester who tests websites? Be a good tester.'
newString = string.replace(oldString, 'test', 'develop', 1)
print(newString)
newString = string.replace(oldString, 'test', 'develop', 2)
print(newString)
newString = string.replace(oldString, 'test', 'develop', 3)

print(newString)
代码将产生以下输出。
I love Python 3.0
I love Python 3.0.
Are you a developer who tests websites? Be a good tester.
Are you a developer who develops websites? Be a good tester.
Are you a developer who develops websites? Be a good developer.
示例 2:使用 对象调用 ()
oldString = 'I love Python 2.0'
newString = oldString.replace('2.0', '3.0')
print(newString)
newString = oldString.replace('2.0', '3.0.')
print(newString)
oldString = 'Are you a tester who tests websites? Be a good tester.'
newString = oldString.replace('test', 'develop', 1)
print(newString)
newString = oldString.replace('test', 'develop', 2)
print(newString)
newString = oldString.replace('test', 'develop', 3)
print(newString)
在这里,它是上面 字符串 () 示例的输出。
I love Python 3.0
I love Python 3.0.
Are you a developer who tests websites? Be a good tester.
Are you a developer who develops websites? Be a good tester.
Are you a developer who develops websites? Be a good developer.
总结
中使用字符串对象的 () 方法或者使用模块

























