Python 如何知道系统默认的编码,并设置系统默认编码 or 编码解码, 以及如何知道系统目录

本文详细介绍了如何在Python中管理系统默认编码,包括查询和设置系统编码的方法。同时,探讨了不同编码如UTF-8、GBK之间的转换,以及在处理中文字符串时常见的错误和解决方案。文章还提供了实用的代码示例,帮助读者理解和应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 如何知道系统默认的编码

  1. import sys

  2. sys.getdefaultencoding()

output:

'utf-8'
  • 设置系统默认编码

         import sys

  1. reload(sys)

  2. sys.setdefaultencoding('utf8')

  • 解码 然后编码

print( " china".decode('utf-8').encode('gbk') ) ##python3 使用 unicode

output:  china

print( u' china')  #python3 使用 unicode

output: china

##################################################################

  1. str and Unicode

str(byte flow)

Unicode(string flow)

 

  1. ASCII(1 byte(7bits+1bit sign) represents 1char, most 127 chars)
    1. à ISO-8859-1(8bits,most 256 chars) à
    2. (GB: Chinese) GB2312 àGBK à GB18030
  2. Unicode(ucs-2, ucs-4) (cost space + time)
  3. UTF-8(efficiency) à UTF-32

Process Chinese string: GBK->Unicode->UTF-8

Decode: GBKàUnicode

Encode: UnicodeàGBK

###################################################################

AttributeError: 'str' object has no attribute 'decode'

OR

b'\xc7\xeb\xca\xe4\xc8\xeb\xc3\xfb\xd7\xd6: '

Solution:

*****************************************************************

#example 1 & example 2

import sys
print(sys.stdin.encoding) #Current: utf-8
print(sys.stdout.encoding) #Current: utf-8

x = input(u"请输入名字: ".encode(sys.stdout.encoding).decode(sys.stdout.encoding))# encodeError solution: ".encode('gbk') "
f = open('1.txt', 'w')
                                         
#Current
f.write(x.encode(sys.stdin.encoding).decode(sys.stdin.encoding))
f.close()

  • 查询系统路径
  1. import sys

  2. sys.path

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

LIQING LIN

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值