Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
字符串
55
5.5
使用
*
重复
可以使用
*
运算符重复某个字符串。尝试在交互式解释器中输入下列内容,查看输出结果:
>>> start = 'Na ' * 4 + '\n'
>>> middle = 'Hey ' * 3 + '\n'
>>> end = 'Goodbye.'
>>> print(start + start + middle + end)
注意,因为
*
的优先级高于
+
,所以字符串会在处理换行之前被重复。
5.6
使用
[]
获取字符
要想获得字符串中的某个字符,在字符串名称之后的方括号内指定其
偏移
即可。第一个字
符(最左边)的偏移是
0
,下一个是
1
,以此类推。最后一个字符(最右边)的偏移可以
使用
–1
指定,这样就用不着挨个数了,继续向左是
–2
–3
,以此类推:
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
>>> letters[0]
'a'
>>> letters[1]
'b'
>>> letters[-1]
'z'
>>> letters[-2]
'y'
>>> letters[25]
'z'
>>> letters[5]
'f'
如果指定的偏移等于或大于字符串长度(记住,偏移范围是从
0
到字符串长度
–1
),就会
产生异常:
>>> letters[100]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223