2014-09-30 263 views
0

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

str1 = 'aBcdJohnsonzZz' 
str2 = 'asdVJohnsonkkk' 

预期结果如下:

str1 = 'BJohnsonZ' 
str2 = 'VJohnson' 
+0

您使用的是什么Python版本? – 2014-09-30 03:17:19

+2

如果“约翰逊”**没有出现在字符串中,您希望发生什么? – 2014-09-30 03:28:07

回答

3

可以分割字符串,检查它有分隔符,不是翻译了小写字母,如:

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 
3

str.partition()是你的朋友在这里:

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 

使用例:

>>> munge("aBcdJohnsonzZz", "Johnson") 
'BJohnsonZ' 
>>> munge("asdVJohnsonkkk", "Johnson") 
'VJohnson' 
+0

尝试:'munge('NoMatchWordHere','Johnson')':) – 2014-09-30 03:24:12

+0

@JonClements诚实地说,我认为结果根据规范是正确的 - 如果没有发生“Johnson”,字符串中的所有字母都是在它之前。 – 2014-09-30 03:25:39

+0

嗯......这可能是真的,但如果它没有发生,那么在它之后就不会有任何* ...所以在*之前去除小写字母* *在*之后没有任何意义... – 2014-09-30 03:27:30

0

不完全是非常简单,流线型的,但你可以做这样的事情(部分基于零比雷埃夫斯)

(编辑,以反映错误)

def remove_lower(string): 
    return ''.join(filter(str.isupper, string)) 

def strip_johnson(input_str): 
    prefix, match, postfix = input_str.partition("Johnson") 
    return (
     remove_lower(prefix) + 
     match + 
     remove_lower(postfix) 
    ) 
+0

尽管'.strip(lower)'将用于示例数据 - 它不会删除所有*小写字母,只是在字符串的首尾处,请尝试:''KlotsoflowercaselettershereK'strip(lower )'例如 – 2014-09-30 03:31:18

+1

......就像是@JonClements一样...你也需要改变'suffix'或'postfix'中的一个。 – 2014-09-30 03:32:07

+0

啊地狱啊,以为我当时很聪明:/ – Mause 2014-09-30 03:39:24

0

有几种方法可以解决这个问题。这是我能想到的最简单的一个。这个想法是分三部分来解决。首先,你需要知道中间的字符串。在你的情况下,'约翰逊'。然后你可以删除前面部分的小写字母和后面的部分。似乎

def removeLowercaseAround(full, middle): 
    stop_at = full.index(middle) #the beginning of the name 
    start_again = stop_at+len(middle) #the end of the name 
    new_str = ''; #the string we'll return at the end 

    for i in range(stop_at): #for each char until the middle starts 
     if not full[i].islower(): #if it is not a lowercase char 
      new_str += full[i] #add it to the end of the new string 

    new_str+=middle #then add the middle char 

    for i in range(start_again, len(full)): #do the same thing with the end 
     if not full[i].islower(): #if it is not a lowercase char 
      new_str += full[i] #add it to the string 
    return new_str 

print removeLowercaseAround('ABcdJohnsonzZZ', 'Johnson') 
0
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) 

使用分区模块的其他方法不考虑你的触发词被反复。如果你有'aBcJohnsonD​​eFJohnsonHiJkL'的情况下,这个例子将起作用,那个特定的情况是你关心的。