Padding multiple character with space - python

前端 未结 3 832
夕颜
夕颜 2021-01-24 01:08

In perl, I can do the following with will pad my punctuation symbols with spaces:

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

In

相关标签:
3条回答
  • 2021-01-24 01:40

    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 ¿ 
    
    0 讨论(0)
  • 2021-01-24 01:51

    Use the format function, and insert a unicode string:

    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)
    

    Output

    this, is a sentence with weird »  symbols …  appearing everywhere ¿ 
    
    0 讨论(0)
  • 2021-01-24 02:05

    You can use re.sub, with \1 as a placeholder.

    >>> 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 ¿
    
    0 讨论(0)
提交回复
热议问题