【问题标题】:Best Way to get numbers value decoded as unicode python将数字值解码为 un​​icode python 的最佳方法
【发布时间】:2015-12-28 11:38:55
【问题描述】:

有没有比从数值中获取 unicode 字符串更好的方法 str(value).decode('utf-8')?

示例用法:

from scipy.io import wavfile

encoding = 'utf-8'
def get_data(basename):
        print (basename).decode(encoding)
        sampFreq, snd  = wavfile.read(basename+'.wav')
        print (u'sample freq: ' + str(sampFreq).decode(encoding) + ' Hz')
        print (u'sample size: '+ str(snd.dtype).decode(encoding))

【问题讨论】:

    标签: python python-2.7 unicode python-unicode


    【解决方案1】:

    您可以直接使用unicode() function

    print u'sample freq: ' + unicode(sampFreq) + u' Hz'
    print u'sample size: '+ unicode(snd.dtype)
    

    或将值分别传递给print(它会将每个部分转换为字符串,并在其间添加空格):

    print u'sample freq:', sampFreq, u'Hz'
    print u'sample size:', snd.dtype
    

    但最佳做法是使用str.format()(这里真的是unicode.format()):

    print u'sample freq: {} Hz'.format(sampFreq)
    print u'sample size: {}'.format(snd.dtype)
    

    请参阅Format String Syntax documentation 了解更多信息。

    【讨论】:

      【解决方案2】:

      不需要解码,str()就足够了,即

      print (u'sample freq: ' + str(sampFreq) + ' Hz')
      print (u'sample size: '+ str(snd.dtype))
      

      但是,这会起作用:

      print(u'sample freq: {} Hz'.format(sampFreq))
      print(u'sample size: {}'.format(snd.dtype))
      

      使用str.format(),是“现代”/首选方式。

      【讨论】:

      • 我的猜测是使用 str 是错误的转换器,所以也有到 unicode 的隐式转换。此外,unicode.format() 用于第二种情况。
      • @MarkTolonen:嘿,谢谢你的建议。也许吧,但如果你知道它无论如何都会以 unicode 结尾,那并不是真的不正确。以这种方式使用str() 可以使这段代码与Python 3 兼容,这不是一个直接的要求,而是一个值得的目标。而unicode.format()str.format() AFAICT 基本相同。不过谢谢!
      猜你喜欢
      • 1970-01-01
      • 2023-04-07
      • 2014-03-13
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多