Python 3数据类型之序列

Python 3中的序列类型包括字符串str、字节串bytes、range、元组tuple以及列表list等。本文通过一些简单的代码来演示序列类型的用法并揭示其实现原理。

字符串str

最简单的使用字符串的方式就是字面值字符串,即用引号括起来的字符串。Python中表示字符串可以用单引号’’,也可以用双引号"",可根据个人习惯而定。对于单行字符串,如果比较长,在源码中一行写不下需要多行,则可以使用续行符\,应注意续行符后面不应该有任何字符。反之,如果要使用多行字符串,一种方法是以转义字符\n来表示换行,另一种方法则是使用三引号来表示。三引号字符串的好处是很直观,引号里写成什么样子显示就是什么样子,跟shell里的here document有些类似。

type('hello')
str
type("hello")
str
s='Hello \
World'
print(s)
Hello World
s='Hello\nWorld'
print(s)
Hello
World
s="""  Hello, World!
Greeting from Python 
with three lines."""
print(type(s))
print(s)
<class 'str'>
  Hello, World!
Greeting from Python 
with three lines.

字符串的一个作用是用做文档帮助字符串。模块、函数和类型都可以有帮助字符串。模块的帮助字符写在文件开头,函数的文档字符串写在函数定义的开头,类型的文档字符串则写在类型定义的开头。一般为了可读性更好,都采用三引号字符串作为文档字符串。模块,函数和类型的文档字符串会被解释器收集到模块对应的模块对象、函数对象和类型对象的__doc__属性中。当然也会在help命令显示相应的模块、函数和类型帮助信息时打印出来。

"""
A test module with help text.
In this module, there is test_func, TestClass and TestClass2.
"""
def test_func():
    """A test function with help text."""
    print('test_func')

class TestClass:
    'A test class with help text.'
    pass

class TestClass2:
    """Another test class with three quotes help text."""
    pass

print(__doc__)
print(test_func.__doc__)
print(TestClass.__doc__)
print(TestClass2.__doc__)
A test module with help text.
In this module, there is test_func, TestClass and TestClass2.

A test function with help text.
A test class with help text.
Another test class with three quotes help text.

字符串属于序列类型,因此它支持下标索引。Python的索引支持正向索引,下标从0到len-1分别表示第一个到最后一个字符;也支持负数反向索引,-1到-len别表示最后一个字符到第一个字符。字符串之所因能支持下标随机索引,是因为str类型实现了__getitem__接口方法。下面的例子演示了用正向、反向索引和__getitem__方法。

s='string'
print(s[0], s[-6], s.__getitem__(0))
print(s[2], s[-3], s.__getitem__(4))
print(s[5], s[-1], s.__getitem__(5))
s s s
r i n
g g g

还可以使用索引范围方便地截取字符子串。索引范围包括起始索引,但是不包括结束索引。按照数学区间的写法,范围索引的含义为[起始索引,结束索引)。如果不指定起始索引则从第一个字符开始(包括),如果不指定结束索引则到最后一个字符(包括)。索引范围还可以指定一个步长,采用"起始索引:结束索引:步长"的形式。因此s[:]就是取整个字符串。见下面几个例子

s="second string"
print(s[:])
print(s[2:8])
print(s[3:])
print(s[:-4])
print(s[1:-1])
print(s[::2])
second string
cond s
ond string
second st
econd strin
scn tig

字符串属于序列类型,而序列都继承了容器接口,支持迭代,因此除了可以用索引遍历,还可以用下面演示的迭代器和反向迭代器进行遍历。

s="third string"
s_iter=iter(s)
s_r_iter=reversed(s)
try:
    while True:
        print(next(s_iter), next(s_r_iter))
except StopIteration:
    pass
t g
h n
i i
r r
d t
  s
s  
t d
r r
i i
n h
g t

字符串类支持+和*这两个数学操作符,但是与数字类型的操作含义不同,+表示连接两个字符串,*则表示将字符串重复多次。字符串也支持比较运算符。

s='Hello ' + 'world'
print(s)
s='Great ' * 3
print(s)
s='Hello'
print(s == "Hello")
Hello world
Great Great Great 
True

字符串是不可变(immutable)序列,也就是说一个字符串对象构造好后,这个对象就不会再改变。如果要改变字符串,则会生成一个新的字符串对象。下面的两个例子说明了这一点。第一个例子中调用字符串对象的upper方法后,得到的大写字符串其实是一个新的str对象,而原来的字符串并未变,从对象id也可以印证;第二个例子将在原字符串后增加一个’.’,实际上新的字符串也是一个新的str对象,而原来的str对象其实并未改变,新str对象赋值给了s。在某种程度上,immutable类型可理解为类型实例为read-only,new instance on write。

s='immutable string'
s1=s
print('id: ', id(s), id(s1))

s.upper()
print(s)
print('id: ', id(s))

s += '.'
print(s)
print('id: ', id(s), id(s1))
id:  4354609760 4354609760
immutable string
id:  4354609760
immutable string.
id:  4354562688 4354609760

字符串str类实现了很多字符串的操作方法,如join、split、find等,详细信息可在Python中用help(str)命令查看。下面是一些简单例子。

s='.'.join(['www', 'google', 'com'])
print(s)
print(s
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值