python - How to delete any occurrences of a string from another string?
问题描述
How do I delete any occurrence of a string from another string?
Ex:
Input: String1 = "himynamemomoohi"
String 2 = "moo"
Output:himynamehi
I was thinking of using if statements like:
if string 2 in string 1:
#remove string 2
But that doesnt work because it would only remove moo and not mo, which is also a part of moo. Hope Im being clear on what im trying to say.
To clarify: String 1 = hihihiiiigrassgrahiii
String 2 = grass
Output: hihihiiihiii
It should remove grass and gra because gra is part of grass.
The output should be such that it only deletes the occurrences of the word starting from the very top. For example, if the string is moohimotoo, and you want to remove moo, you should remove moo and mo from the string. You should not remove oo (too) because it does not start from the very beginning of the string.
解决方案
您可以使用正则表达式:
import re
s1 = 'hihihiiiigrassgrahiii'
s2 = 'grass'
re.sub('|'.join([s2[:i] for i in range(len(s2), 1, -1)]), '', s1)
输出:
'hihihiiiiassahiii'
推荐阅读
- ios - Swift 3:您可以保存裁剪图像的位置并在显示完整图像时访问它吗?
- javascript - 光滑的滑块 - 悬停时暂停并在鼠标离开时播放剩余的秒数
- java - 在 Android 中显示州名以及纬度和经度
- .htaccess - 将 .htaccess 添加到 Cordova
- api - 如何在不使用 API Gateway 的情况下使用 AWS Cognito 进行自定义 Spring REST API 授权
- python - os.getlogin() 没有得到正确的帐户名
- angular - 如何重置清除 Typescript 类中的值
- javascript - 想要将 , 分隔的字符串存储在数组中
- php - 如何从 MyOperators webhook 响应中获取正确的 JSON?
- python - Python Pandas - 将列表转换为系列