用空格填充多个字符-python

用空格填充多个字符-python,python,regex,perl,tokenize,substitution,Python,Regex,Perl,Tokenize,Substitution,在perl中,我可以使用空格填充标点符号来执行以下操作: s/([،;؛¿!"\])}»›”؟%٪°±©®।॥…])/ $1 /g;` 在Python中,我尝试了以下方法: >>> p = u'،;؛¿!"\])}»›”؟%٪°±©®।॥…' >>> text = u"this, is a sentence with weird» symbols… appearing everywhere¿" >>> for i in p: ...

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

s/([،;؛¿!"\])}»›”؟%٪°±©®।॥…])/ $1 /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 ¿ 

但是有没有一种方法可以使用某种占位符符号,例如在
perl
中使用
$1
,我可以在
python
中使用1个regex执行同样的操作?

使用
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 ¿ 

使用
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版本的
$1
\1
,但是您应该使用正则表达式替换而不是简单的字符串替换:

import re

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

print re.sub(p, ur' \1 ', text)
产出:

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

Python版本的
$1
\1
,但是您应该使用正则表达式替换而不是简单的字符串替换:

import re

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

print re.sub(p, ur' \1 ', text)
产出:

this , is a sentence with weird »  symbols …  appearing everywhere ¿ 
您可以使用,
\1
作为占位符

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

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

如果您可以发布单独的问题,而不是将您的问题合并为一个问题,这是首选。这样,它可以帮助人们回答你的问题,也可以帮助其他人寻找至少一个你的问题。谢谢@凯斯,在这种情况下,这几乎是同一个问题;我认为再问一个问题会导致重复。特别是当
\p{Open\u标点符号}
类似于流行需求中的
u''时:=)如果您可以发布单独的问题,而不是将您的问题合并为一个问题,则更可取。这样,它可以帮助人们回答你的问题,也可以帮助其他人寻找至少一个你的问题。谢谢@凯斯,在这种情况下,这几乎是同一个问题;我认为再问一个问题会导致重复。特别是当
\p{Open\u标点符号}
类似于流行需求的
u''时:=)OP希望摆脱
for
循环。你的答案在语义上与原来的答案没有什么不同,只是你的答案运行得快了一点。OP希望摆脱
for
循环。你的答案在语义上与原文没有什么不同,只是你的答案跑得快一点。