2. 字符串

字符串是由零个或多个字符组成的不可变序列,用引号(单引号、双引号、三引号)创建。

创建与转义

python
s1 = 'hello, world!'
s2 = "你好,世界!"
s3 = '''多行字符串
第二行'''

# 转义字符:\n 换行,\t 制表符,\\ 反斜杠,\' 单引号
print('\'hello\'')  # 'hello'

# 原始字符串:r 前缀,不转义
print(r'\n 不是换行')  # \n 不是换行

▶ 运行结果:

输出
'hello'
\n 不是换行

字符编码

python
print(ord('A'))    # 65,获取字符的 Unicode 编码
print(chr(66))     # 'B',将编码转换为字符
print(ord('中'))    # 20013

# 字符串编码为字节串
print('中文'.encode('utf-8'))  # b'\xe4\xb8\xad\xe6\x96\x87'
print(len('中'))    # 1(一个字符)
print(len('中'.encode('utf-8')))  # 3(UTF-8 编码占3字节)

▶ 运行结果:

输出
65
B
20013
b'\xe4\xb8\xad\xe6\x96\x87'
1
3

运算:拼接、重复、成员、比较

python
# 拼接与重复
print('hello' + ', ' + 'world')  # hello, world
print('!' * 3)                    # !!!

# 成员运算
print('wo' in 'hello, world')     # True
print('py' not in 'hello')        # True

# 比较(按字符编码逐位比较)
print('A' < 'a')  # True(65 < 97)

▶ 运行结果:

输出
hello, world
!!!
True
True
True

索引与切片

python
s = 'abc123456'
print(s[0])      # a(正向索引)
print(s[-1])     # 6(反向索引)
print(s[2:5])    # c12(切片 [2,5))
print(s[::-1])   # 654321cba(反转)
print(s[::2])    # ac246(步长为2)

▶ 运行结果:

输出
a
6
c12
654321cba
ac246
⚠️ 字符串不可变

字符串是不可变类型,不能通过 s[0] = 'X' 修改字符。字符串方法(如 upper())会返回新字符串,原字符串不变。

常用方法

分类方法说明
大小写upper() / lower()全大写 / 全小写
capitalize()首字母大写
title()每个单词首字母大写
查找find(sub)查找子串位置,找不到返回 -1
index(sub)同 find,找不到抛出 ValueError
修剪strip()去除两端空白(或指定字符)
lstrip() / rstrip()去左端 / 去右端
替换replace(old, new)替换子串
拆分合并split(sep)按分隔符拆分为列表
join(list)将列表合并为字符串
判断isdigit()是否全为数字
isalpha()是否全为字母
startswith(s)是否以 s 开头
python
# split 与 join 是最常用的字符串操作
s = 'I love Python'
words = s.split()        # ['I', 'love', 'Python']
print('-'.join(words))   # I-love-Python

# split 实用技巧:一行输入多个值
x, y, z = input("输入三个值,逗号分隔:").split(',')
x, y, z = map(int, input("输入三个整数:").split())

# strip 去除用户输入的首尾空格
name = input("请输入姓名:").strip()