用空格填充多个字符 - python [英] Padding multiple character with space - python

查看:68
本文介绍了用空格填充多个字符 - python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

perl 中,我可以用空格填充标点符号:

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

Python 中,我试过了:

<预><代码>>>>p = u'،;؛¿!"\])}»›"؟%٪°±©®।॥...'>>>text = u"this,是一个带有奇怪»符号的句子……到处都是……">>>对于 p 中的 i:... text = text.replace(i, ' '+i+' ')...>>>文本u'this, 是一个带有奇怪的 \xbb 符号 \u2026 出现在任何地方 \xbf 的句子>>>打印文本这是一个带有奇怪 » 符号的句子……到处都是 ¿

但是有没有办法使用某种占位符符号,例如$1perl 中,我可以在 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆