2017-06-20 64 views
0

我想根據標記來變換輸入字符串。從字符串中刪除一串非特定字符的方法

因此,("Hail Mary #Run quick see\ncd!sawce", ["#", "!"])將刪除標記後面的所有字符,但直到反斜槓或字符串結束。

該案將成爲("Hail Mary #Run quick see\ncd!sawce", ["#", "!"])

Hail Mary cd

我寫了這個:

def solution(string, markers): 
    orig = string.strip() 
    wholeList = [] 
    newString = orig 
    for char in orig: 
     for j in markers: 
      if char == j: 
       i = orig.index(char) 
       newString = orig[:i].strip() 
       wholeList.append(newString) 
     if char == "\\": 
      i = orig.index(char) 
      orig = orig[i:] 

return "".join(wholeList) 
+1

這對於正則表達式很簡單。 – Barmar

+0

爲什麼它保留'\ ncd'?這裏沒有反斜槓,這是一個換行符。 – Barmar

+1

爲什麼*#之前的空格不包含在輸出中? – trincot

回答

3

首先,你需要逃避你反斜線,如果你打算在y中有字面反斜槓我們的字符串。

然後,您可以使用正則表達式替換:

import re 
s = "Hail Thor #Run quick see\\ncd!sawce" 
print(re.sub(r"[#!].*?(?=[\\]|$)", "", s)) # Hail Thor \ncd 

如果你打算有一個換行符\n,你想去除去,直到下一個換行符,那麼它是更容易,如默認.不匹配換行符:

import re 
s = "Hail Thor #Run quick see\ncd!sawce" 
print(re.sub(r"[#!].*", "", s)) # Hail Thor 
            # cd 
+0

或使用原始字符串。 – Barmar

+0

事實上,這也可以發揮作用:'r'Hail Thor #Run快看\ ncd!sawce「'。 – trincot

+0

在這個問題中,我不想改變輸入。如果用戶輸入一個換行符,那麼我想包含該元素後面的字符。 – Enesxg

0

雖然我會@trincot同意使用正則表達式,我做了一個替代解決方案:

def solution(text, markers): 
    # If all the markers are used or 
    # there are no markers return text 
    if len(markers) < 1: 
     return text.strip() 
    else: 
     # Get the first marker 
     marker = markers.pop(0) 
     # Split the string with the marker 
     before, after = text.split(marker) 
     # Split the remaining string at a newline 
     after = after.split("\n", 1) 
     if len(after) > 1: 
      end = "\n" + after[-1] 
     else: 
      end = "" 
     text = before.strip() + end 
     return solution(text, markers)