python 2.7 中文编码

2 篇文章 0 订阅
2 篇文章 0 订阅

python 2.7 中文编码

文件编码 "-- coding:utf-8 --"

  • 文件编码的意思是,以“utf-8”为例,在当前文件中,可以存在“utf-8”的中文字符,如下例子,如果控制台是utf-8编码的,那就会输出“你好世界! hello world ”
    # -*- coding:utf-8 -*-
    def test3():
        str1 = u"你好世界! "
        str2 = u"hello world "
        print str1+str2
    test3()

字符编码

  • 如果控制台是gbk上,则会输出乱码,如何解决呢?下面代码:
    # -*- coding:utf-8 -*-
    def test3():
        str1 = u"你好世界! "
        str2 = u"hello world "
        print (str1+str2).encode("gbk")
    test3()
  • 如果你的python程序读进来的系统路径是gbk编码的(比如:你的python程序在windows默认编码gbk下,命令行接受了一个中文路径的参数;或者你的python代码中读取了一个用户的环境变量,这个环境变量中带中文,如何让代码识别这个路径呢?)请看下面代码:
    # -*- coding:utf-8 -*-
    def test1():
        user_tmp = os.getenv("tmp")//C:\Users\测试1\AppData\Local\Temp
        file_dir = os.path.join(user_tmp.decode("gbk"), "update_dir")
        os.mkdir(file_dir)
    test1()

有些程序代码可能需要如下改动

# -*- coding:utf-8 -*-
def test3();
    user_tmp = os.getenv("tmp") //C:\Users\测试1\AppData\Local\Temp
    file_dir = os.path.join(user_tmp.decode("gbk"), "updatedir")
    deploy_path = os.path.join(file_dir, "deploy.exe")
    cmd = "\"%s\"" % deploy_path
    p = subprocess.Popen(cmd.encode("gbk"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
test3()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值