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

后端 未结 6 1546
清酒与你
清酒与你 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条回答
  •  我在风中等你
    2020-12-16 01:04

    In Python 3, cleanest is to use str.translate and str.maketrans:

    FULLWIDTH_TO_HALFWIDTH = str.maketrans('1234567890',
                                           '1234567890')
    def fullwidth_to_halfwidth(s):
        return s.translate(FULLWIDTH_TO_HALFWIDTH)
    

    In Python 2, str.maketrans is instead string.maketrans and doesn’t work with Unicode characters, so you need to make a dictionary, as Josh Lee notes above.

提交回复
热议问题