2016-08-09 174 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:我写了一个小的更新到我的答案,关于为什么或什么时候最好使用非贪婪的正则表达式。 –

相关问题