Python 字符串减法:去除子字符串
要从一个字符串中去除另一个字符串,可以使用字符串的 replace() 方法或者使用正则表达式。
使用 replace() 方法的示例:
string1 = 'Hello, World!'
string2 = 'o'
new_string = string1.replace(string2, '')
print(new_string) # Output: Hell, Wrld!
使用正则表达式的示例:
import re
string1 = 'Hello, World!'
string2 = 'o'
new_string = re.sub(string2, '', string1)
print(new_string) # Output: Hell, Wrld!
这两种方法都会从第一个字符串中删除所有出現在第二个字符串中的字符。
原文地址: https://www.cveoy.top/t/topic/qhAG 著作权归作者所有。请勿转载和采集!