2015-12-28 44 views
0

有沒有更好的方法從數字值獲取Unicode字符串比 str(value).decode('utf-8')獲取解碼爲Unicode的數字值的最佳方法

實例應用:

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)) 

回答

1

無需解碼,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() ,是「現代」/最好的方式來做到這一點。

+0

嗯,爲什麼downvote? – mhawke

+0

我的猜測是使用'str'是錯誤的轉換器,所以也有隱式轉換到'unicode'。另外,在第二種情況下使用'unicode.format()'。 –

+0

@MarkTolonen:嗨,謝謝你的建議。也許,但是如果你知道它最終會以unicode結尾,那麼它並不是真的不正確。以這種方式使用'str()'使得這個代碼與Python 3兼容,不是一個直接的要求,而是一個有價值的目標。 ''unicode.format()'和str.format()'AFAICT基本相同。但是,謝謝! – mhawke

3

您可以使用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瞭解更多信息。

相關問題