zoukankan      html  css  js  c++  java
  • python处理中文字符

    1.在py文件中使用中文字符

    unicode.py文件内容如下所示:

    # -*- coding:utf-8 -*-
    
    str_ch = '我们women'
    uni_ch = u'我们women'
    
    print "type:", type(str_ch), "content:", str_ch,  repr(str_ch)
    print "type:", type(uni_ch), "content:", uni_ch,  repr(uni_ch)
    


    需要在文件第一行输入以下内容:“# -*- coding: utf-8 -*-",否则在执行时将会抛出如下异常信息。

    SyntaxError: Non-ASCII character 'xe6' in file unicode.py on line 3, but no encoding declared; 

    在声明编码类别后,执行结果如下:

    type: <type 'str'> content: 我们women 'xe6x88x91xe4xbbxacwomen'
    type: <type 'unicode'> content: 我们women u'u6211u4eecwomen'

    使用命令“od -t c unicode.py”查看文件在硬盘上的内容如下:

    0000000   #       -   *   -       c   o   d   i   n   g   :   u   t   f
    0000020   -   8       -   *   -       s   t   r   _   c   h       =
    0000040       ' 346 210 221 344 273 254   w   o   m   e   n   '     u 
    0000060   n   i   _   c   h       =       u   ' 346 210 221 344 273 254
    0000100   w   o   m   e   n   '       p   r   i   n   t       "   t
    0000120   y   p   e   :   "   ,       t   y   p   e   (   s   t   r   _
    0000140   c   h   )   ,       "   c   o   n   t   e   n   t   :   "   ,
    0000160       s   t   r   _   c   h   ,           r   e   p   r   (   s
    0000200   t   r   _   c   h   )     p   r   i   n   t       "   t   y
    0000220   p   e   :   "   ,       t   y   p   e   (   u   n   i   _   c
    0000240   h   )   ,       "   c   o   n   t   e   n   t   :   "   ,    
    0000260   u   n   i   _   c   h   ,           r   e   p   r   (   u   n
    0000300   i   _   c   h   )  

    注:346为8进制。

    可以看到中文字符在硬盘中以utf-8形式保存,在执行时被python解释器读入内存,遇到非ascii字符时,需要用指定的编码进行转换。


    2. Python中字符类型str和unicode

    Unicode使用code point描述字符,一个code point就是一个整数值,16-bit。所以,unicode字符串就是一串code point。

    书写的方式可以是:

    uni_str = u"我们"
    uni_str = u"xac"    # 2个16进制数表示
    uni_str = u"u1234"    #  4个16进制数表示
    uni_str = u"U00008000"    # 8个16进制数表示

    str是8bit,从0-255。书写方式如下:

    s = '0'
    s = 'x30'
    s = '60'
    s = chr(48)
    # ord(s)  都是48

    encoding:将unicode字符串转换成一串bytes(0-255)。

    python默认的encoding和decoding都是ascii,当数值超过128时都将会报编码或解码错误。

  • 相关阅读:
    go_base_03_if_for_switch_goto_流程控制
    go_base_02_dataType_常用数据类型
    go_base_01_var_const_变量和常量
    go_install_01_golang开发环境安装配置
    go_install_02_golang插件安装
    数据封装和私有属性
    类变量 实例变量 属性查找顺序
    微服务架构之「 服务注册 」
    Nginx配置https证书
    Go:go程序报错Cannot run program "C:UsersdellAppDataLocalTemp\___go_build_hello_go.exe" (in directory "…………"):该版本的 %1 与你运行的 Windows 版本不兼容。
  • 原文地址:https://www.cnblogs.com/riskyer/p/3271342.html
Copyright © 2011-2022 走看看