2014-09-30 256 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'的情況下,這個例子將起作用,那個特定的情況是你關心的。