[英]Python string not printing properly in PowerShell
行# coding=utf-8
仅有助于编写unicode文字,对于纯字节字符串没有用处。 无论如何,假设您的Python文件是UTF-8编码的, str = str.decode('utf-8')
您提供了正确的unicode字符串。
但是正如Ansgar Wiechers所说的那样,在声明编码时,更简单的方法是直接使用Unicode乱码:
str = u"35 μg/m3"
简而言之,Windows控制台对UTF8的支持很差。 常见编码为win1252(latin1变体)或cp850本机OEM字体。 除非要显式处理显式编码,否则最好的选择是直接显示unicode字符串:
#!/usr/bin/python
# coding=utf-8
str ="35 μg/m3"
str = str.decode('utf-8') # str is now an unicode string
print(str)
如果要显式使用latin1,并且使用的是TrueType字体(如Lucida Console或Consolas),则可以执行以下操作:
chcp 1252
python .\encoding.py
与
#!/usr/bin/python
# coding=utf-8
str ="35 μg/m3"
str = str.decode('utf-8') # str is now an unicode string
str = str.encode('latin1') # str is now an latin1 encoded byte string
print(str)
Python 2.7默认情况下不使用Unicode字符串,因此您基本上有2个选择:
将字符串定义为Unicode字符串文字( u"..."
):
# coding=utf-8 str = u"35 µg/m3" print(str)
这样,您可以像预期的那样简单地使用字符串,因此我更喜欢这种方法。
将字符串定义为常规字符串文字并对其进行解码:
# coding=utf-8 str = "35 \\xc2\\xb5g/m3" print(str.decode('utf-8'))
如果使用此方法,则即使文件另存为UTF-8,也需要将特殊字符作为十六进制值(UTF-8中的µ
是字符序列0xC2,0xB5)放置。
示范:
PS C:\> $PSVersionTable.PSVersion.ToString() 4.0 PS C:\> C:\Python27\python.exe -V Python 2.7.11 PS C:\> Get-Content .\test.py -Encoding UTF8 # coding=utf-8 str1 = "35 \xc2\xb5g/m3" print(str1) print(str1.decode('utf-8')) str2 = u"35 µg/m3" print(str2) PS C:\> C:\Python27\python.exe .\test.py 35 ┬Ág/m3 35 µg/m3 35 µg/m3
您的解码/编码无效:
# coding=utf-8
s1 = "35 μg/m3"
s2 = s1.decode('utf-8')
s3 = s2.encode('utf-8') #ready for printing?
print s1==s3
如果您的源是声明的UTF-8,则s1
是一个已经过UTF-8编码的字节字符串。 将其解码为Unicode字符串( s2
)并将其重新编码为UTF-8只会为您提供原始字节字符串。
接下来,Windows控制台未默认为UTF-8,因此打印这些字节将以控制台编码解释它们,在我的系统上是:
import sys
print sys.stdout.encoding
print s3
输出:
cp437
35 ┬╡g/m3
打印Unicode字符串并使它们正确理解的正确方法是实际打印Unicode字符串。 它们将通过Python编码为控制台编码并正确显示(假设控制台字体和编码支持字符)。
# coding=utf-8
s = u"35 µg/m3"
print s
输出:
35 µg/m3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.