2013-01-11 44 views
0

添加一个新行我有以下文字:应用re.sub在python

xml = ''' 
<accessibility_info> 
    <accessibility role="captions" available="true" /> 
</accessibility_info> 
<crew_member billing="top" 
    <display_name>John Viscount</display_name> 
</crew_member> 
<products> 
    <territory>GB</territory> 
</products>''' 

我需要删除以下<crew_member>块。这是我目前在做什么:

clean_xml = re.sub('<crew_member>.*</crew_member>', '', metadata_contents, 
        flags=re.DOTALL) 

但是,还加入了新行:

<accessibility_info> 
    <accessibility role="captions" available="true" /> 
</accessibility_info> 

<products> 
    <territory>GB</territory> 
</products> 

我将如何改变正则表达式来剥离换行符一样,所以它看起来像:

<accessibility_info> 
    <accessibility role="captions" available="true" /> 
</accessibility_info> 
<products> 
    <territory>GB</territory> 
</products>' 
+1

只需将'\ n'添加到匹配字符串的末尾。 – Anorov

+0

这不是它添加了一个换行符,而是你没有删除它。 – saulspatz

回答

2

试试这个

print re.sub('<crew_member([^\>]*)>.*</crew_member>\n', '', xml, flags=re.DOTALL)

0

我知道这有点旧,但我想说新的一行实际上来自用于将新文本写入文件的方法。如果我使用print()添加了新行,但如果我使用例如sys.stdout.write(),则不会添加新行。