Python: How can I replace full-width characters with half-width characters?

后端 未结 6 1530
清酒与你
清酒与你 2020-12-16 00:51

If this was PHP, I would probably do something like this:

function no_more_half_widths($string){
  $foo = array(\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'7\',\'8         


        
6条回答
  •  萌比男神i
    2020-12-16 01:28

    I don't think there's a built-in function to do multiple replacements in one pass, so you'll have to do it yourself.

    One way to do it:

    >>> src = (u'1',u'2',u'3',u'4',u'5',u'6',u'7',u'8',u'9',u'10')
    >>> dst = ('1','2','3','4','5','6','7','8','9','0')
    >>> string = u'a123'
    >>> for i, j in zip(src, dst):
    ...     string = string.replace(i, j)
    ... 
    >>> string
    u'a123'
    

    Or using a dictionary:

    >>> trans = {u'1': '1', u'2': '2', u'3': '3', u'4': '4', u'5': '5', u'6': '6', u'7': '7', u'8': '8', u'9': '9', u'0': '0'}
    >>> string = u'a123'
    >>> for i, j in trans.iteritems():
    ...     string = string.replace(i, j)
    ...     
    >>> string
    u'a123'
    

    Or finally, using regex (and this might actually be the fastest):

    >>> import re
    >>> trans = {u'1': '1', u'2': '2', u'3': '3', u'4': '4', u'5': '5', u'6': '6', u'7': '7', u'8': '8', u'9': '9', u'0': '0'}
    >>> lookup = re.compile(u'|'.join(trans.keys()), re.UNICODE)
    >>> string = u'a123'
    >>> lookup.sub(lambda x: trans[x.group()], string)
    u'a123'
    

提交回复
热议问题