用空格填充多个字符 - python [英] Padding multiple character with space - python
本文介绍了用空格填充多个字符 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 perl
中,我可以用空格填充标点符号:
s/([،;؛¿!"\])}»›"؟%٪°±©®।॥...])/$1/g;`
在 Python
中,我试过了:
但是有没有办法使用某种占位符符号,例如$1
在 perl
中,我可以在 python
中用 1 个正则表达式做同样的事情吗?
解决方案
$1
的 Python 版本是 \1
,但是你应该使用正则表达式替换而不是简单的字符串替换:
导入重新p = ur'([،;؛¿!"\])}»›"؟%٪°±©®।॥…])'text = u"this,是一个带有奇怪»符号的句子……到处都是……"打印 re.sub(p, ur' \1 ', text)
输出:
this ,是一个带有奇怪 » 符号的句子……到处都是 ¿
In perl
, I can do the following with will pad my punctuation symbols with spaces:
s/([،;؛¿!"\])}»›"؟%٪°±©®।॥…])/ $1 /g;`
In Python
, I've tried this:
>>> 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 ¿
But is there a way to use some sort of a placeholder symbol, e.g. $1
in perl
where I can do the same in python
with 1 regex?
解决方案
Python version of $1
is \1
, but you should use regex substitution instead of simple string replace:
import re
p = ur'([،;؛¿!"\])}»›"؟%٪°±©®।॥…])'
text = u"this, is a sentence with weird» symbols… appearing everywhere¿"
print re.sub(p, ur' \1 ', text)
Outputs:
this , is a sentence with weird » symbols … appearing everywhere ¿
这篇关于用空格填充多个字符 - python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文