笔记五:python2字符串

一:学习内容

  • 字符串类型
  • 字符串类型判断
  • 字符串类型互转
  • 字符串小练习

二:字符串类型

1. basestring

在python字符串相关数据类型为:strunicode他们都是basestring的子类可见strunicode是两种不同类型字符串对象

2. 字节字符串类型

byteString='hello world!'

可以看到这个byteString的类型为str

3. unicode字符串类型(在普通字符串前面加个u)

unicodeString=u'hello Unicode world!'

可以看到这个unicodeString的类型为unicode

 

三:字符串类型判断

1. 判断是否是字符串(包括str和unicode)

#encoding=utf-8

s = "hello normal string"

u = u'hello unicode'

if isinstance(s,basestring):

    print u'是字符串'

if isinstance(u,basestring):

    print u'是字符串'

运行结果为:无论str字符串还是unicode字符串都属于basestring类中

2. 判断是否是unicode

#encoding=utf-8

s = "hello normal string"

u = u'hello unicode'

if isinstance(s,unicode):

    print s,u'unicode'

if isinstance(u,unicode):

    print u,u'unicode'

运行结果为:

3. 判断是否是str

#encoding=utf-8

s = "hello normal string"

u = u'hello unicode'

if isinstance(s,str):

    print s,u'str'

if isinstance(u,str):

    print u,u'str'

运行结果为:

四:字符串类型互转

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

#encoding=utf-8

s="byte string"

print type(s)

#str 转 unicode

u = s.decode()

print type(u)

#uncode 转 str

backToBytes = u.encode()

print type(backToBytes)

可以看到上面的unicodedecode都没有指定编码解码的名称,此时会用系统默认的编码。

2. 指定编码解码类型进行互转

#encoding=utf-8

s = "hello normal string"

print u"字节字符串",type(s)

 

#str 转 unicode

u = s.decode("UTF-8" )

print u"Unicode字符串",type(u)

#uncode 转 str 

backToBytes = u.encode( "UTF-8" )

print u"字节字符串",type(backToBytes)

运行结果为:

五:字符串小练习

1. 小练习一:输出字符串中奇数坐标字符串

a = 'gloryroad'

''.join([a[x] for x in xrange(len(a)) if x%2==1])

2. 小练习二:将字符串大变小写,小写变大写输出

s='adbABC'

s.swapcase()

3. 小练习三:将字符串abcdefgccc顺序第一个c变成f然后输出整个字符串

s1='abcdefgccc'

s2=''

flag=True

for i in s1:

    if i=='c' and flag:

        s2+='f'

        flag=False

    else:

        s2+=i

print s2

运行结果为:

4. 小练习四:输出1000以内包含334,153

print [x for x in range(1001) if '3' in str(x)]

上面的练习也许各位初学者不能全部都看懂,别急,后续的python学习笔记中我们会就每一个细节进行一一学习。

原文地址:https://www.cnblogs.com/miaomiaokaixin/p/6590611.html