下标与切片 · Python 从零开始
怎样从字符串里取出一个字母,或者其中一段?
课程目录为什么需要它
文字无处不在:名字、消息、编号、文件名。经常只需要其中一部分:名字的首字母、卡号的后 4 位、日期里的年份。Python 用下标 Index 取任意位置的字符,用切片 Slice 取任意一段。
直觉理解
字符串是一排编了号的格子,编号从 0 开始:
| P | y | t | h | o | n |
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
| -6 | -5 | -4 | -3 | -2 | -1 |
word[0]是 "P",word[5]是 "n"。负数从末尾倒着数:word[-1]是 "n"。len(word)是 6,也就是字符个数。最后一个下标是len(word) - 1。- 切片
word[start:stop]从start取到stop之前(不包括stop):word[0:2]是 "Py"。省略一边就一直取到头:word[2:]是 "thon"。
定义
下标 Index
An index is the position of an item in a sequence; Python indexes start at 0.下标是元素在序列中的位置;Python 的下标从 0 开始。
切片 Slice
A slice s[start:stop] is a new string containing the characters from index start up to, but not including, index stop.切片 s[start:stop] 是一个新字符串,包含从下标 start 到 stop 之前(不含 stop)的字符。
示例
取出片段
动手试试试试在方括号里换别的数字。
word = "Python"
print(word[0], word[-1])
print(word[0:2], word[2:])
print(len(word))逐步执行
- L2下标 0 是第一个字符,-1 是最后一个。
P n - L3[0:2] 取下标 0 和 1(不含 2);[2:] 从 2 取到末尾。
Py thon - L4len 数出字符的个数。
6
拼接字符串
动手试试+ 把字符串粘在一起,但不会自动加空格。
first = input()
last = input()
print(first + " " + last)
print(first[0] + last[0])输入(每次 input() 读一行)
Grace Hopper
逐步执行
- L3三个字符串拼在一起:名、空格、姓。
Grace Hopper - L4各取第一个字符:缩写。
GH
常见错误
从 1 开始数
第一个字符是 s[0],不是 s[1]。s[len(s)] 会报 IndexError;最后一个是 s[len(s) - 1],或者直接写 s[-1]。
切片不包括结束位置
s[1:3] 只有 2 个字符(下标 1 和 2)。切片长度 = stop − start。
小测验
1. 这段代码会输出什么?
s = "hello"
print(s[1])查看答案
答案:B
下标从 0 开始,所以下标 1 是第二个字符。
2. 这段代码会输出什么?
print("abcdef"[2:4] + "!")查看答案
答案:A
下标 2 和 3 是 c 和 d,不包括 4。
动手练习
3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。
- 预测输出切香蕉
准确写出程序的输出。
- 改需求首字母、尾字母、长度
这段程序打印单词的第一个字母。改成打印三行:第一个字母、最后一个字母、长度。
- 从零写姓名缩写
读入名和姓(两行)。打印带点的缩写,比如 Ada 和 Lovelace 打印
A.L.。
本课术语
| 术语 | 中文 | 英文定义 |
|---|---|---|
| Index | 下标 | The position of an item in a sequence, starting from 0. |
| Slice | 切片 | A part of a sequence taken with [start:stop], excluding stop. |
| len() | len() 长度函数 | A function that returns the number of items in a sequence. |
| Concatenation | 拼接 | Joining strings end to end with +. |