用 space - python 填充多个字符

Padding multiple character with space - python

perl 中,我可以使用空格填充标点符号来执行以下操作:

s/([،;؛¿!"\])}»›”؟%٪°±©®।॥…])/  /g;` 

Python 中,我试过这个:

>>> p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…'
>>> text = u"this, is a sentence with weird» symbols… appearing everywhere¿"
>>> for i in p:
...     text = text.replace(i, ' '+i+' ')
... 
>>> text
u'this, is a sentence with weird \xbb  symbols \u2026  appearing everywhere \xbf '
>>> print text
this, is a sentence with weird »  symbols …  appearing everywhere ¿ 

但是有没有办法使用某种占位符符号,例如</code> in <code>perl 我可以在 python 中用 1 个正则表达式做同样的事情?

使用format函数,并插入一个unicode字符串:

p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…'
text = u"this, is a sentence with weird» symbols… appearing everywhere¿"
for i in p:
    text = text.replace(i, u' {} '.format(i))

print(text)

输出

this, is a sentence with weird »  symbols …  appearing everywhere ¿ 

Python </code> 的版本是 <code>,但您应该使用正则表达式替换而不是简单的字符串替换:

import re

p = ur'([،;؛¿!"\])}»›”؟%٪°±©®।॥…])'
text = u"this, is a sentence with weird» symbols… appearing everywhere¿"

print re.sub(p, ur'  ', text)

输出:

this , is a sentence with weird »  symbols …  appearing everywhere ¿ 

您可以使用 re.sub,将 </code> 作为占位符。</p> <pre><code>>>> p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…' >>> text = u"this, is a sentence with weird» symbols… appearing everywhere¿" >>> text = re.sub(u'([{}])'.format(p), r' ', text) >>> print text this, is a sentence with weird » symbols … appearing everywhere ¿