首页 > 解决方案 > 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.

标签: pythonpython-3.x

解决方案


您可以使用正则表达式:

import re

s1 = 'hihihiiiigrassgrahiii'
s2 = 'grass'

re.sub('|'.join([s2[:i] for i in range(len(s2), 1, -1)]), '', s1)

输出:

'hihihiiiiassahiii'

推荐阅读