Python字符串去除指定字符:replace()方法详解
要从字符串中删除某个子字符串,可以使用字符串的replace()方法。
示例代码如下:
string = 'Hello World'
substring = 'o'
new_string = string.replace(substring, '')
print(new_string) # 输出:Hell Wrld
在上面的例子中,我们将字符串Hello World
赋值给变量string
,然后定义了一个要删除的子字符串o
赋值给变量substring
。
然后,我们使用字符串的replace()方法将substring
替换为空字符串''
,并将结果赋值给new_string
。
最后,我们打印new_string
,输出结果为Hell Wrld
,即删除了字符串中的所有o
字符。

原文地址: http://www.cveoy.top/t/topic/pdmw 著作权归作者所有。请勿转载和采集!