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版)
56
5
>>> name = 'Henny'
>>> name.replace('H', 'P')
'Penny'
>>> 'P' + name[1:]
'Penny'
并没有改变
name
的值。交互式解释器只是打印出了替换结果。
5.7
使用分片提取子串
可以使用
分片
从字符串中提取
子串
(字符串的一部分)。分片是通过一对方括号、起始偏
start
、结束偏移
end
以及两者之间可选的步长
step
定义的。可以忽略其中某些部分。
分片包括从
start
开始到
end
结束的所有字符:
[:]
提取整个字符串;
[:
start
:]
start
提取至字符串末尾;
[:
end
]
从字符串开始提取至
end
–1
[
start
:
end
]
start
提取至
end
–1
[
start
:
end
:
step
]
start
提取至
end
–1
,每隔
step
个字符提取一个。
与之前一样,偏移从左至右为
0
1
2...
,依次递增
;从右至左为
–1
–2
–3...
,依次递
减。如果省略
start
,那么分片将从
0
(字符串起始位置)开始提取;如果省略
end
,则分
片会使用字符串结尾。
下面来创建一个全部为英语小写字母的字符串:
>>> letters = 'abcdefghijklmnopqrstuvwxyz'
:
等同于
0:
(整个字符串):
>>> letters[:]
'abcdefghijklmnopqrstuvwxyz'
从偏移
20
提取至结尾:
>>> letters[20:]
'uvwxyz'
从偏移
10
提取至结尾:
>>> letters[10:] ...
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