第三讲:字符串类型判断与转换

字符串类型判断与转换

一、字节字符串和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'>

 

posted on 2019-05-19 15:50  Cwenky  阅读(1441)  评论(0编辑  收藏  举报