人人都能学编程
English 开始学习
课程 2 · Python 入门第 5 课 / 共 14 课免费阅读

下标与切片 · Python 从零开始

怎样从字符串里取出一个字母,或者其中一段?

课程目录

为什么需要它

文字无处不在:名字、消息、编号、文件名。经常只需要其中一部分:名字的首字母、卡号的后 4 位、日期里的年份。Python 用下标 Index 取任意位置的字符,用切片 Slice 取任意一段。

直觉理解

字符串是一排编了号的格子,编号从 0 开始:

Python
012345
-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))
逐步执行
  1. L2下标 0 是第一个字符,-1 是最后一个。P n
  2. L3[0:2] 取下标 0 和 1(不含 2);[2:] 从 2 取到末尾。Py thon
  3. L4len 数出字符的个数。6

拼接字符串

动手试试

+ 把字符串粘在一起,但不会自动加空格。

first = input()
last = input()
print(first + " " + last)
print(first[0] + last[0])
输入(每次 input() 读一行)
Grace
Hopper
逐步执行
  1. L3三个字符串拼在一起:名、空格、姓。Grace Hopper
  2. 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])
  1. A
    h
  2. B
    e
  3. C
    l
查看答案

答案:B

下标从 0 开始,所以下标 1 是第二个字符。

2. 这段代码会输出什么?

print("abcdef"[2:4] + "!")
  1. A
    cd!
  2. B
    bc!
  3. C
    cde!
查看答案

答案:A

下标 2 和 3 是 c 和 d,不包括 4。

动手练习

3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。

  1. 预测输出切香蕉

    准确写出程序的输出。

  2. 改需求首字母、尾字母、长度

    这段程序打印单词的第一个字母。改成打印三行:第一个字母、最后一个字母、长度。

  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 +.