Python从字符串中删除指定子字符串且子字符串不分大小写,多次出现,请举出三种方法
时间: 2024-05-21 11:13:13 浏览: 14
可以使用replace()方法、正则表达式和split()方法等来删除指定子字符串,以下是三种方法的示例代码:
1. 使用replace()方法删除指定子字符串:
string = "Hello, World! hello, Python!"
substring = "hello"
new_string = string.replace(substring, "")
new_string = new_string.replace(substring.capitalize(), "")
print(new_string)
输出: "Hello, World! Python!"
2. 使用正则表达式删除指定子字符串:
import re
string = "Hello, World! hello, Python!"
substring = "hello"
new_string = re.sub(substring, "", string, flags=re.IGNORECASE)
print(new_string)
输出: "Hello, World! , Python!"
3. 使用split()方法删除指定子字符串:
string = "Hello, World! hello, Python!"
substring = "hello"
new_string = "".join(filter(lambda x: x.lower() != substring.lower(), string.split()))
print(new_string)
输出: "Hello, World! Python!"
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)