Python 教程 / 字符串

字符串

字符串是Python中最常用的数据类型之一。本章将详细介绍字符串的各个方面,包括基本操作、格式化、常用方法等。

字符串基础

字符串是用单引号'双引号"括起来的文本:

>>> s1 = 'hello'
>>> s2 = "world"
>>> print(s1, s2)
hello world
 

转义字符

如果字符串内部需要包含特殊字符,可以使用转义字符\

>>> print('I\'m learning Python')
I'm learning Python
>>> print("He said: \"Hello!\"")
He said: "Hello!"
>>> print('Line1\\nLine2')
Line1
Line2
>>> print('Path: C:\\Users\\Name')
Path: C:\Users\Name
 

常用转义字符表

转义字符 含义 示例
\\反斜杠'\\\\''\\'
\'单引号'It\\'s'"It's"
\"双引号"He said: \\\""He said: "Hello"
\n换行换到下一行
\t制表符Tab键效果
\r回车回到行首

原始字符串

如果有很多反斜杠,可以用原始字符串r'',它会忽略转义:

>>> path = r'C:\Users\Admin\Documents'
>>> print(path)
C:\Users\Admin\Documents
 

注意

原始字符串的结尾不能单独使用反斜杠:r'C:\' 是错误的!

多行字符串

三引号'''"""可以创建多行字符串:

>>> poem = '''春眠不觉晓,
...处处闻啼鸟,
...夜来风雨声,
...花落知多少。'''
>>> print(poem)
春眠不觉晓,
处处闻啼鸟,
夜来风雨声,
花落知多少。
 

字符串索引与切片

字符串就像一个字符数组,每个字符都有对应的索引:

┌─────────────────────────────────────────────────────────────┐
│              字符串 "Python" 的索引示意图                   │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   字符串:     P     y     t     h     o     n               │
│               │     │     │     │     │     │               │
│   正向索引:   0     1     2     3     4     5               │
│   反向索引:  -6    -5    -4    -3    -2    -1               │
│                                                             │
└─────────────────────────────────────────────────────────────┘ 

索引访问

>>> s = 'Python'
>>> s[0]
'P'
>>> s[2]
't'
>>> s[-1]
'n'
>>> s[-3]
'h'
 

切片操作

切片语法:s[start:end],包含start,不包含end:

>>> s = 'Python'
>>> s[0:3]
'Pyt'
>>> s[1:4]
'yth'
>>> s[:3]
'Pyt'
>>> s[3:]
'hon'
>>> s[:]
'Python'
>>> s[::2]
'Pto'    # 步长为2
>>> s[::-1]
'nohtyP' # 反转字符串
 
┌─────────────────────────────────────────────────────────────┐
│                  切片原理图                                │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   s = "Python"                                             │
│                                                             │
│   s[0:3] → "Pyt"                                          │
│   ├─┤├─┤├─┤                                              │
│   0  1  2  3  ← 取0,1,2,不包含3                          │
│                                                             │
│   s[::2] → "Pto"  (每2个取一个)                           │
│   ├─┤ ├─┤ ├─┤                                             │
│   0     2     4                                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘ 

字符串常用方法

Python为字符串提供了丰富的内置方法:

大小写转换

>>> 'hello'.upper()
'HELLO'
>>> 'HELLO'.lower()
'hello'
>>> 'hello'.capitalize()
'Hello'
>>> 'hello world'.title()
'Hello World'
 

查找与替换

>>> 'hello'.find('ll')
2
>>> 'hello'.find('x')
-1
>>> 'hello'.count('l')
2
>>> 'hello'.replace('l', 'r')
'herro'
 

判断相关

>>> 'hello'.startswith('hel')
True
>>> 'hello'.endswith('lo')
True
>>> '123'.isdigit()
True
>>> 'abc'.isalpha()
True
>>> 'abc123'.isalnum()
True
>>> '   '.isspace()
True
 

分割与连接

>>> 'a,b,c'.split(',')
['a', 'b', 'c']
>>> 'hello world'.split()
['hello', 'world']
>>> '-'.join(['a', 'b', 'c'])
'a-b-c'
>>> '  hello  '.strip()
'hello'
>>> 'hello'.ljust(10, '-')
'hello-----'
>>> 'hello'.center(10, '-')
'--hello---'
 

字符串格式化

Python有多种字符串格式化方法:

f-string(推荐,最现代)

f-string是Python 3.6+引入的,用f'...{}...'语法:

>>> name = 'Alice'
>>> age = 20
>>> f'我叫{name},今年{age}岁'
'我叫Alice,今年20岁'
>>> f'{age * 2}'
'40'
>>> f'{3.14159:.2f}'
'3.14'
 

format()方法

>>> '我叫{},今年{}岁'.format('Bob', 25)
'我叫Bob,今年25岁'
>>> '{1} {0}'.format('world', 'hello')
'hello world'
>>> '{name}的成绩是{score:.1f}'.format(name='Tom', score=95.678)
'Tom的成绩是95.7'
 

%格式化(旧式,但仍常用)

>>> 'Hello %s' % 'World'
'Hello World'
>>> '%d + %d = %d' % (1, 2, 3)
'1 + 2 = 3'
>>> '%.2f' % 3.14159
'3.14'
 

格式化对比

方式 示例 特点
f-string f'{name}' 推荐,最简洁
format() '{}'.format(x) 灵活,功能强大
% '%s' % x C语言风格,老代码常见

字符串编码

字符串在计算机中以字节形式存储。Python 3默认使用UTF-8编码:

>>> '中文'.encode('utf-8')
b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'
>>> b'\\xe4\\xb8\\xad\\xe6\\x96\\x87'.decode('utf-8')
'中文'
 

编码小知识

  • ASCII:只能表示英文字母和符号,用1个字节
  • UTF-8:支持全球文字,用1-4个字节(中文通常3个字节)
  • GBK:中文编码,用2个字节(Windows中文版常用)

字符串不可变

重要:字符串是不可变类型,不能直接修改:

s = 'hello'
s[0] = 'H'   # 错误!字符串不能这样修改
 

TypeError: 'str' object does not support item assignment

如果需要修改,应该创建新字符串:

>>> s = 'hello'
>>> s = 'H' + s[1:]     # 创建新字符串
>>> s
'Hello'
 

练习题

练习1:字符串切片

给定字符串 s = 'Python Programming'

  1. 取出 "Python"
  2. 取出 "Programming"
  3. 反转整个字符串

练习2:字符串方法

实现以下操作:

  1. 将 "hello world" 首字母大写
  2. 统计 "hello" 中 'l' 出现的次数
  3. 将 "a-b-c" 用 '_' 连接成 "a_b_c"

小结

  • 字符串用单引号双引号表示,r''表示原始字符串;
  • 字符串支持索引切片,语法 s[start:end:step]
  • 常用字符串方法:upper/lower/find/replace/split/join/strip等;
  • 格式化推荐使用f-string,如 f'{name}'
  • 字符串是不可变的,不能直接修改,只能创建新的字符串。
🐍 Python 在线代码编辑器
📝 运行结果