Python学习笔记(四)序列类型与字符串

序列类型

其他程序语言用数组(Array)来处理,Python中则成为序列(Sequence),存放于序列中的数据称为元素(Element)或项目(item)。

序列类型可以将多个数据群聚在一起,根据其可变性(mutability)将序列分成不可变序列(Immutable Sequences)和可变序列(Mutable Sequences)。

序列与迭代器

Python通过容器(Container)进行迭代操作。迭代器(Iterator)类型是一种复合式数据类型,可将不同数据放在容器内迭代。迭代器对象会以迭代器协议(Iterator protocol)作为沟通标准。迭代器有两个接口(Interface):

  • Iterator(迭代器) 借助内置函数next()返回容器的下一个元素。
  • Iterable(可迭代的) 通过内置函数iter()返回迭代器对象。
>>> data = [12,34,55]
>>> num = iter(data)
>>> type(num)
<class 'list_iterator'>
>>> next(num)
12
>>> next(num)
34
  • 序列(Sequence)数据包含list,tuple,str。
>>> number = [10,20]
>>> type(number)
<class 'list'>
>>> data = ('a','b','c')
>>> type(data)
<class 'tuple'>
  • 序列中存放的数据成为元素(element),获取其位置,使用[]运算符配合索引编号(index)。
>>> month = ['Jan','Feb','Mar','Apr']
>>> month[2]
'Mar'
>>> month[-1]
'Apr'
  • 成员运算符in/not in
>>> number = [10,20]
>>> 10 in number
True
>>> 30 not in number
True
  • +/*运算符
>>> [20,30] + [10,20]
[20, 30, 10, 20]

字符串

除了数字,Python还可以处理字符串,这可以用多种方式表示。他们可以被括在单引号 ('...') 或双引号 ("...") 中,二者等价 [2]\ 可以用于转义'︰

>>> 'spam eggs'  # single quotes
'spam eggs'
>>> 'doesn\'t'  # use \' to escape the single quote...
"doesn't"
>>> "doesn't"  # ...or use double quotes instead
"doesn't"
>>> '"Yes," he said.'
'"Yes," he said.'
>>> "\"Yes,\" he said."
'"Yes," he said.'
>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
如果你不想让 \ 被解释为特殊字符开头的字符,您可以通过添加 r 使用 原始字符串
>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name

  • 内置函数enumerate()提供索引
>>> word = 'good'
>>> print(list(enumerate(word)))
[(0, 'g'), (1, 'o'), (2, 'o'), (3, 'd')]
word = 'good'
for id, data in enumerate(word):
    print([id], data, end=' ')
[0] g [1] o [2] o [3] d 

切片

字符串的字符具有顺序性,使用[]运算符来提取字符串中的单个字符,或某个范围的子字符串,这个操作被称为切片(Slicing)。
运算 说明
s[n]按指定序列值获取序列的某个元素
s[n:m]从索引值n到m-1来获取若干元素
s[n:]从索引值n开始到最后一个元素
s[:m]从索引值0开始到m-1个元素
s[:]表示会复制一份序列元素
s[::-1]将整个序列元素反转
  • 内置函数slice()
>>> wd = 'Programming'
>>> wd2 = wd[slice(7)] #slice(stop)
>>> wd2
'Program'
>>> wd2 = wd[slice(1, 6, 2)] #slice(start, stop[, step])
>>> wd2
'rga'

格式化字符串

%运算符
>>> word = 'Python'
>>> print('Hello World %s'%word)
Hello World Python
内置函数format()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值