zoukankan      html  css  js  c++  java
  • 第三讲:字符串类型判断与转换

    字符串类型判断与转换

    一、字节字符串和unicode字符串

    1、basestring

    在python中字符串的相关数据类型为str和unicode,他们都是basestring的子类,可见str和unicode是两种不同类型的字符串对象。

    2、创建字符串

    byteString='hello string'

    unicodeString=u'hello string'

    type()查看变量类型

    二、判断是否是字符串(str和unicode):

    1、用isinstance()函数判断:判断一个对象的变量类型,如果是返回True,不是返回False 

    # encoding=utf-8
    byteString='hello normal string'
    unicodeString=u'hello unicode'
    
    if isinstance(byteString,basestring):
        print byteString, u'是字符串'
    if isinstance(unicodeString,basestring):
        print unicodeString,u'是字符串'
    
    运行结果:
    hello string 是字符串
    hello unicode 是字符串
    
     

    2、判断是否是unicode:

    # encoding=utf-8
    byteString='hello normal string'
    unicodeString=u'hello unicode'
    
    if isinstance(byteString,unicode):
        print byteString, u'是unicode'
    if isinstance(unicodeString,unicode):
        print unicodeString,u'是unicode'

    运行结果: hello unicode 是unicode

     3、判断是否是str:

    byteString='hello string'
    unicodeString=u'hello unicode'
    
    if isinstance(byteString,str):
        print byteString, u'是str'
    if isinstance(unicodeString,str):
        print unicodeString,u'是str'

    运行结果: hello string 是str

     三、不同字符串类型互转

    1、不指定编码解码类型进行互转--使用系统默认编码:

    s='hello string'
    print type(s)
    
    u=s.decode() #str 转 unicode
    print type(u)
    
    backToStr=u.encode()  #unicode 转 str
    print type(backToStr)
    运行结果:
    <type 'str'> <type 'unicode'> <type 'str'>
    
    

    2、指定编码解码类型进行转换:

    # encoding=utf-8
    
    s='hello string'
    print type(s)
    
    u=s.decode('utf-8') #str 转 unicode
    print type(u)
    
    backToStr=u.encode('utf-8')  #unicode 转 str
    print type(backToStr)
    
    运行结果:
    <type 'str'>
    <type 'unicode'>
    <type 'str'>
  • 相关阅读:
    shell 格式化输出
    Linux tar 修改终端命令
    uniqu 用法
    HashMap按照value值进行排序
    汇编语言系列教程之基础入门 (一)
    Linux权限管理
    linux用户管理
    vim的tab键设定
    HTTP请求(GET与POST区别)和响应
    JS eval()
  • 原文地址:https://www.cnblogs.com/wenxiacui/p/10889526.html
Copyright © 2011-2022 走看看