Python String replace()方法教程

Python字符串数据类型提供 replace() 方法,以便用提供的字符替换或更改指定的字符。replace()方法返回新的或替换的字符串。

null

String replace()方法语法

Python string replace()方法有以下语法,其中最多可以提供3个参数,但一般来说,2个参数的版本是最流行的。replace()方法是一个内置方法,其中不需要导入任何模块和提供的字符串类型的对象。

STRING.replace( OLDVALUE , NEWVALUE , COUNT)
  • 字符串是我们将替换 旧值 使用新值。替换的字符串版本将由replace()方法返回。
  • 旧值 是字符串中当前存在的可以更改的值。 旧值 是必需的。
  • 新价值 将被设置为新值并替换为 旧值 . 新价值 是必需的。
  • 计数 是一个可选参数,其中替换操作将执行多少次。默认情况下,如果未提供计数,则没有限制。

String replace()方法示例

现在做一些关于replace()方法的例子。我们会

s1 = "This is a text where the replace method will be called"s2 = "one plus one is not equal to the one"print( s1.replace( "e" , "3" ) )print( s2.replace( "one" , "two" ) )print( s2.replace( "one" , "two" , 1 ) )print( s1.replace( "one" , "two" , 2 ) )
图片[1]-Python String replace()方法教程-yiteyi-C++库

使用多重/链式替换方法

在某些情况下,您可能需要快速、简单地替换多个字符。可以在多行中多次使用replace()方法,但也可以以链接方式在单行中使用replace()方法。在下面的示例中,我们将在字符串中多次调用replace方法。

s = "one plus one is not equal to the one"print( s2.replace( "one" , "two" ).replace( "two" , "three" ) )
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享