2016-08-09 172 views
-2

我有Python中的字符串:如何從字符串中刪除標有特殊字符的子字符串?

Tt = "This is a <\"string\">string, It should be <\"changed\">changed to <\"a\">a nummber." 

print Tt 

'This is a <"string">string, It should be <"changed">changed to <"a">a nummber.' 

你看,有些話在這部分<\" \">.

我的問題是,如何刪除那些重複的部分(與指定字符分隔)重複?

結果應該是這樣的:

'This is a string, It should be changed to a nummber.' 
+3

向我們展示您的代碼。 – Julien

+0

與我們分享您已經嘗試的方法是表達您面臨的困難的好方法。我們可以解決您嘗試中具有問題的特定領域。 – Lix

+1

加油!你可以想出一個更好的標題。 –

回答

5

使用正則表達式:

import re 
Tt = re.sub('<\".*?\">', '', Tt) 

注意?*後。它使得表達式非貪婪 ,因此它儘可能匹配<\"\">之間的這麼幾個符號。

詹姆斯的解決方案只會在工作時的情況,限界子 從一個字符(<>)只包含。在這種情況下,可以使用否定符號[^>]。如果要刪除用字符序列分隔的子字符串(例如使用beginend),則應使用非貪婪的正則表達式(即.*?)。

1

我會使用一個快速的正則表達式:

import re 
Tt = "This is a <\"string\">string, It should be <\"changed\">changed to <\"a\">a number." 
print re.sub("<[^<]+>","",Tt) 
#Out: This is a string, It should be changed to a nummber. 

啊 - 類似伊戈爾的崗位上,他通過位打我。如果表達式中不包含另一個開始標籤「<」,則表示不匹配表達式,因此它只會匹配一個開始標籤,後跟一個結束標籤「>」。

+0

@James:我寫了一個小的更新到我的答案,關於爲什麼或什麼時候最好使用非貪婪的正則表達式。 –

相關問題