在python中如何从字符串中删除子字符串?

2024-10-01 02:19:48 发布

您现在位置:Python中文网/ 问答频道 /正文

如何删除这些字符串中“Johnson”前后的所有小写字母?在

str1 = 'aBcdJohnsonzZz'
str2 = 'asdVJohnsonkkk'

预期结果如下:

^{pr2}$

Tags: 字符串johnson小写字母str1str2pr2abcdjohnsonzzzasdvjohnsonkkk
3条回答
import re
def foo(input_st, keep_st):
    parts = input_st.split(keep_st)
    clean_parts = [re.sub("[a-z]*", "", part) for part in parts]
    return keep_st.join(clean_parts)

其他使用分区模块的方法似乎没有考虑到触发器字的重复。这个例子在你有“aBcJohnsonDeFJohnsonHiJkL”的情况下是有效的,在这种情况下,这个特殊的情况是你关心的。在

^{}您的朋友在这里:

def munge(text, match):
    prefix, match, suffix = text.partition(match)
    prefix = "".join(c for c in prefix if not c.islower())
    suffix = "".join(c for c in suffix if not c.islower())
    return prefix + match + suffix

示例用法:

^{pr2}$

可以对字符串进行分区,检查是否有分隔符,然后翻译出小写字母,例如:

from string import ascii_lowercase as alc

str1 = 'aBcdJohnsonzZz'
p1, sep, p2 = str1.partition('Johnson')
if sep:
    str1 = p1.translate(None, alc) + sep + p2.translate(None, alc)
print str1

相关问题 更多 >