目录
字符串
在 Python 中,字符串是 Unicode 字符的不可变序列。根据 UNICODE 标准,每个字符都有一个唯一的数值。但是,即使所有字符都是数字,整个序列也没有任何数值。为了将字符串与数字和其他标识符区分开来,字符序列在其字面表示形式中被包含在单引号、双引号或三引号中。因此,1234 是一个数字(整数),但 '1234' 是一个字符串。
字符串基本概念
-
什么是字符串
- 在 Python 中,字符串(
str
)是用 引号 括起来的一段文本。 - 引号可以是单引号
'...'
、双引号"..."
,甚至三引号'''...'''
或"""..."""
(多行字符串)。
pythons1 = 'hello' s2 = "world" s3 = '''多行 字符串'''
- 在 Python 中,字符串(
-
不可变性(Immutable)
- Python 中的字符串是不可变的:创建后不能直接修改,只能重新生成新的字符串。
pythons = "python" # s[0] = "P" # ❌ 报错:字符串不能直接修改 s = "P" + s[1:] # ✅ 通过新建字符串修改 print(s) # Python
创建字符串
最基本的方式:引号
Python 提供了三种写法:
- 单引号 :
'hello'
- 双引号 :
"hello"
- 三引号 :
'''hello'''
或"""hello"""
特点:
- 单引号和双引号效果完全一样,主要是为了方便(比如字符串里有
'
时可以用"
包裹)。 - 三引号可以创建 多行字符串,常用在文档字符串(docstring)。
python
s1 = 'Hello'
s2 = "World"
s3 = '''这是一个
多行字符串'''
print(s1, s2, s3)
空字符串
可以直接用 ''
或 ""
:
python
empty = ''
print(len(empty)) # 0
字符串切片
在 Python 中,字符串是Unicode 字符的有序序列。字符串中的每个字符在序列中都有一个唯一的索引。索引从 0 开始。字符串中第一个字符的位置索引为 0。索引向字符串末尾不断递增。
如果字符串变量声明为 var="HELLO PYTHON",则字符串中每个字符的索引如下

Python 允许通过索引访问字符串中的任意单个字符。在本例中,0 是字符串的下限,11 是上限。因此,var[0] 返回 H,var[6] 返回 P。如果方括号中的索引超出上限,Python 会引发 IndexError。
在下面的例子中,我们通过索引访问字符串的字符。
python
var = "HELLO PYTHON"
print(var[0])
print(var[7])
print(var[11])
print(var[12])
运行代码时,它将产生以下输出
H
Y
N
ERROR!
Traceback (most recent call last):
File "<main.py>", line 5, in <module>
IndexError: string index out of range
Python 序列类型(因此也是字符串对象)的独特特性之一是它也支持负索引方案。在上面的示例中,我们使用的是正索引方案,索引从左到右递增。如果是负索引,则末尾字符的索引为 -1,索引从右到左递减,因此第一个字符 H 的索引为 -12。
让我们使用负索引来获取 N、Y 和 H 字符。
python
var = "HELLO PYTHON"
print(var[-1])
print(var[-5])
print(var[-12])
执行上述代码后,将给出以下结果
N
Y
H
因此,我们可以使用正索引或负索引从字符串中检索字符。
在 Python 中,字符串是不可变对象。如果对象一旦存储在某个内存位置就无法就地修改,则该对象是不可变的。你可以借助其索引从字符串中检索任何字符,但不能将其替换为其他字符。
在以下示例中,字符 Y 在 HELLO PYTHON 中的索引为 7。尝试将 Y 替换为 y,看看会发生什么。
python
var="HELLO PYTHON"
var[7]="y"
print (var)
它将产生以下输出
Traceback (most recent call last):
File "C:\Users\users\example.py", line 2, in <module>
var[7]="y"
~~~^^^
TypeError: 'str' object does not support item assignment
TypeError 是因为字符串是不可变的。
切片的基本语法
语法形式:
python
s[start:end:step]
- start :起始索引(包含),默认
0
- end :结束索引(不包含),默认
len(s)
- step :步长(每次跳几个),默认
1
,可以是负数
举例:
python
s = "abcdefg"
print(s[0:3]) # abc (索引0到2)
print(s[2:5]) # cde (索引2到4)
print(s[:4]) # abcd (从开头到3)
print(s[3:]) # defg (从3到结尾)
print(s[:]) # abcdefg (完整拷贝)
与正索引一样,负索引也可以用于切片。
python
var="HELLO PYTHON"
print ("var:",var)
print ("var[3:8]:", var[3:8])
print ("var[-9:-4]:", var[-9:-4])
它将产生以下输出
var: HELLO PYTHON
var[3:8]: LO PY
var[-9:-4]: LO PY
步长 step
- 正数步长(从左往右取)
python
print(s[::2]) # aceg (隔一个取一个)
print(s[1:6:2]) # bdf (从索引1开始,每隔2个取1个,直到5)
- 负数步长(反向取)
python
print(s[::-1]) # gfedcba (字符串反转)
print(s[5:2:-1]) # fed (从索引5到3,逆序)
切片的规律
-
切片永远遵循:左闭右开 [start, end)
-
超出索引不会报错,只会截到有效范围:
pythonprint(s[0:100]) # abcdefg print(s[-100:3]) # abc
-
step = 0 会报错:
pythonprint(s[::0]) # ValueError
切片操作返回一个新字符串。可以很好地执行字符串操作,例如连接,或者对切片后的字符串进行切片。
python
var="HELLO PYTHON"
print ("var:",var)
print ("var[:6][:2]:", var[:6][:2])
var1=var[:6]
print ("slice:", var1)
print ("var1[:2]:", var1[:2])
它将产生以下输出
var: HELLO PYTHON
var[:6][:2]: HE
slice: HELLO
var1[:2]: HE
常见技巧与应用
- 复制字符串
python
copy = s[:]
- 反转字符串
python
rev = s[::-1]
- 获取奇数位/偶数位字符
python
odd = s[1::2] # bdf
even = s[0::2] # aceg
- 截取固定长度子串
python
sub = s[2:5] # cde
- 去掉首尾字符
python
mid = s[1:-1] # bcdef
- 每 n 个字符取一个
python
every3 = s[::3] # adg
修改字符串
Python 中,字符串(str类的对象)是不可变对象(immutable)。
所谓"修改字符串",本质是 创建一个新的字符串对象,原始字符串保持不变。
与列表不同,不能直接覆盖、插入、删除字符。
常见修改方式
使用字符串方法
- 替换子串
python
s = "hello world"
print(s.replace("world", "Python")) # hello Python
print(s.replace("l", "L", 2)) # heLLo world
- 改变大小写
python
s = "hello world"
print(s.upper()) # HELLO WORLD
print(s.capitalize()) # Hello world
- 删除或替换空白
python
s = " hello "
print(s.strip()) # hello
- 批量替换
python
s = "hello world"
table = str.maketrans("hel", "HEL")
print(s.translate(table)) # HELLo worLd
- 正则替换(复杂规则)
python
import re
s = "I have 2 cats and 3 dogs"
print(re.sub(r"\d", "#", s)) # I have # cats and # dogs
切片 + 拼接
适合修改、插入、删除:
python
s = "abcdefg"
print(s[:2] + "XY" + s[4:]) # abXYefg (修改)
print(s[:2] + "X" + s[2:]) # abXcdefg (插入)
print(s[:2] + s[3:]) # abdefg (删除)
转换为列表再修改
字符串转列表(可变),改完再拼接。
python
s = "hello"
lst = list(s)
lst[0] = "H"
print("".join(lst)) # Hello
使用 array
模块
把字符串转成 array('u', ...)
(Unicode字符数组),可在原地修改:
python
import array
s = "WORD"
arr = array.array('u', s)
arr.insert(3, "L")
print(arr.tounicode()) # WORLD
使用 io.StringIO
把字符串放进 StringIO
流对象,可以像文件一样写入修改:
python
import io
s = "WORD"
sio = io.StringIO(s)
sio.seek(3)
sio.write("LD")
print(sio.getvalue()) # WORLD
字符串连接
在 Python 中,字符串连接就是把两个或多个字符串拼接在一起,形成一个新的字符串对象。Python 提供了多种方式来实现字符串连接。
使用 +
运算符
+
在 Python 中可以用来拼接字符串,结果是一个新的字符串。
python
str1 = "Hello"
str2 = "World"
str3 = str1 + str2
print(str3) # HelloWorld
- 如果想在字符串中加空格,可以插入
" "
:
python
str3 = str1 + " " + str2
print(str3) # Hello World
- 优点:简单直观
- 缺点:大量循环拼接时性能差,因为每次都会生成新的字符串对象
使用 +=
运算符
+=
等价于 s = s + "..."
:
python
s = "Hello"
s += " "
s += "World"
print(s) # Hello World
同样适合少量拼接,不推荐在循环中大量使用。
使用乘法运算符 *
进行重复拼接
*
运算符可以重复字符串:
python
s = "ha" * 3
print(s) # hahaha
也可以和 +
一起用:
python
str1 = "Hello"
str2 = "World"
str3 = str1 + str2 * 3
print(str3) # HelloWorldWorldWorld
str4 = (str1 + str2) * 3
print(str4) # HelloWorldHelloWorldHelloWorld
注意:
*
优先级高于+
,需要括号控制顺序。
推荐的高效方法:join()
python
words = ["Hello", "World", "Python"]
s = " ".join(words)
print(s) # Hello World Python
- 专门为字符串拼接设计,效率高
- 特别适合在循环中拼接大量字符串
- 所有元素必须是字符串
格式化字符串拼接
- f-string(Python 3.6+)
python
name = "Alice"
age = 20
s = f"My name is {name}, I am {age} years old."
print(s)
str.format()
python
s = "My name is {}, I am {} years old.".format("Alice", 20)
print(s)
%
占位符
python
s = "My name is %s, I am %d years old." % ("Alice", 20)
print(s)
f-string 推荐使用,清晰且性能好。
特殊拼接技巧
- 多行拼接
python
s = ("Hello"
" World"
" Python")
print(s) # Hello World Python
- 使用
*
重复拼接
python
s = ("ha" + "ho") * 3
print(s) # hahohahohaho
方法 | 适用场景 | 特点 |
---|---|---|
+ / += |
少量拼接 | 简单直观,循环中效率低 |
* |
重复字符串 | 简单,优先级高于 + |
"".join(iterable) |
大量拼接 | 高效,元素必须是字符串 |
f-string | 插入变量 | 清晰,推荐使用 |
str.format() |
插入变量 | 可控,兼容性好 |
% |
老方法 | 兼容老代码,不推荐新项目 |
多行拼接 | 可读性 | Python 会自动连接括号中的字符串 |
io.StringIO | 大量循环 | 高效,适合大量拼接 |
字符串格式化
字符串格式化就是 在字符串中动态插入值,把变量、表达式或函数结果插入到字符串中,生成新的字符串。Python 提供多种方式来实现。
使用 %
运算符(老方法)
%
运算符,也叫 格式化操作符 ,类似 C 语言中的 printf
风格。
基本用法
name = "Tutorialspoint"
print("Welcome to %s!" % name)
# 输出: Welcome to Tutorialspoint!
%s
→ 字符串%d
→ 整数%f
→ 浮点数(默认 6 位小数)
多个变量
name = "Alice"
age = 25
print("%s is %d years old" % (name, age))
# 输出: Alice is 25 years old
控制浮点精度
pi = 3.1415926
print("Pi = %.2f" % pi) # Pi = 3.14
注意:这是老方法,Python 3 已经推荐使用
format()
或 f-string。
使用 str.format()
方法
str.format()
是 Python 2.7+ / 3.x 推荐的方法。
- 用
{}
定义占位符 - 可以通过位置或关键字填充
基本用法
s = "Welcome to {}"
print(s.format("Tutorialspoint"))
# 输出: Welcome to Tutorialspoint
多个占位符
s = "{} is {} years old"
print(s.format("Alice", 25))
# 输出: Alice is 25 years old
使用关键字参数
s = "{name} is {age} years old"
print(s.format(name="Alice", age=25))
# 输出: Alice is 25 years old
控制浮点精度
pi = 3.1415926
print("Pi = {:.2f}".format(pi)) # Pi = 3.14
对齐和填充
text = "Hi"
print("{:<10}".format(text)) # 左对齐: "Hi "
print("{:>10}".format(text)) # 右对齐: " Hi"
print("{:^10}".format(text)) # 居中: " Hi "
f 字符串(格式化字符串字面量,Python 3.6+)
f-string 是 Python 现代推荐的格式化方式,性能好,可读性高。
基本用法
name = "Alice"
age = 25
s = f"{name} is {age} years old"
print(s) # Alice is 25 years old
表达式支持
item1_price = 2500
item2_price = 300
total = f'Total: {item1_price + item2_price}'
print(total) # Total: 2800
浮点精度控制
pi = 3.1415926
print(f"Pi = {pi:.2f}") # Pi = 3.14
对齐和填充
text = "Hi"
print(f"{text:<10}") # 左对齐
print(f"{text:>10}") # 右对齐
print(f"{text:^10}") # 居中
使用 string.Template
类
Template
类提供了另一种占位符方式,用 $
表示。
from string import Template
s = "Hello and Welcome to $name!"
t = Template(s)
new_s = t.substitute(name="Tutorialspoint")
print(new_s)
# 输出: Hello and Welcome to Tutorialspoint!
- 占位符用
$name
- 支持
substitute()
(必须提供值)或safe_substitute()
(缺少值时不会报错)
转义字符
在 Python 中,转义字符 是以反斜杠 \
开头的特殊字符序列,用于表示字符串中不能直接输入的字符或具有特殊含义的字符。
转义字符的基本概念
- 转义字符的作用:告诉解释器该字符序列具有特殊含义。
- 语法:
\
+ 特殊字符。 - 示例:
python
s = "Hello\nWorld"
print(s)
输出:
python
Hello
World
解释:\n
表示换行符,Python 会在此处换行。
原始字符串(Raw String)
- 在字符串前加
r
或R
前缀,表示 原始字符串,其中的转义符不会被解释:
python
normal = "Hello\nWorld"
print(normal)
# Hello
# World
raw = r"Hello\nWorld"
print(raw)
# Hello\nWorld
重要区别:
- 普通字符串会解析转义字符
- 原始字符串不会解析,常用于正则表达式和文件路径
常用转义字符表
转义序列 | 含义 | 示例 |
---|---|---|
\\ |
反斜杠 \ |
'C:\\Users\\Alice' |
\' |
单引号 ' |
'It\'s Python' |
\" |
双引号 " |
"Hello \"World\"" |
\a |
ASCII 响铃 (BEL) | print("Hello\a") |
\b |
ASCII 退格 (Backspace) | 'Hel\blo' → 输出 Helo |
\f |
ASCII 换页 (Form Feed) | 'Hello\fWorld' |
\n |
换行 (LF) | 'Hello\nWorld' |
\r |
回车 (CR) | 'Hello\rWorld' |
\t |
水平制表符 (TAB) | 'Hello\tWorld' |
\v |
垂直制表符 (VT) | 'Hello\vWorld' |
\ooo |
八进制表示字符 | \101 → A |
\xhh |
十六进制表示字符 | \x41 → A |
\ + 换行 |
忽略换行符,实现多行字符串 | 'Hello\ World' → 输出Hello World |
python
# 忽略换行
s = 'This string will not include \
backslashes or newline characters.'
print(s)
# This string will not include backslashes or newline characters.
# 反斜杠
s = 'The \\ character is called backslash'
print(s)
# The \ character is called backslash
# 单引号与双引号
s1 = 'Hello \'Python\''
s2 = "Hello \"Python\""
print(s1) # Hello 'Python'
print(s2) # Hello "Python"
# 退格
s = 'Hel\blo'
print(s) # Helo
# 响铃
s = 'Hello\a'
print(s) # 电脑可能响一声
# 换行
s = 'Hello\nPython'
print(s)
# Hello
# Python
# 制表符
s = 'Hello\tPython'
print(s)
# Hello Python
# 换页
s = "Hello\fWorld"
print(s)
# 八进制
s = "\101"
print(s) # A
# 十六进制
s = "\x41"
print(s) # A
字符串方法
Python 的 字符串对象(str 类)是不可变的,意味着所有方法都返回新的字符串,而不会修改原字符串本身。字符串方法可以按功能分类:
大小写转换方法
这些方法用于调整字符串中字母的大小写。
方法 | 描述 | 示例 |
---|---|---|
capitalize() |
将字符串首字母大写,其余小写 | "hello world".capitalize() → 'Hello world' |
casefold() |
将字符串转换为小写,适合 UNICODE 比较 | "ß".casefold() → 'ss' |
lower() |
将所有字符转换为小写 | "Hello".lower() → 'hello' |
swapcase() |
大小写反转 | "Hello".swapcase() → 'hELLO' |
title() |
每个单词首字母大写 | "hello world".title() → 'Hello World' |
upper() |
将所有字符转换为大写 | "hello".upper() → 'HELLO' |
示例:
python
s = "hello world"
print(s.capitalize()) # Hello world
print("ß".casefold()) # ss (比 lower 更强,支持 Unicode)
print("HELLO".lower()) # hello
print("Hello".swapcase()) # hELLO
print("hello world".title()) # Hello World
print("python".upper()) # PYTHON
对齐方法
用于控制字符串在指定宽度内的对齐方式。
方法 | 描述 | 示例 |
---|---|---|
center(width, fillchar=' ') |
居中对齐,填充字符可选 | "Hi".center(10, '*') → '****Hi****' |
ljust(width, fillchar=' ') |
左对齐 | "Hi".ljust(10, '-') → 'Hi--------' |
rjust(width, fillchar=' ') |
右对齐 | "Hi".rjust(10, '-') → '--------Hi' |
expandtabs(tabsize=8) |
将制表符转为空格 | 'a\tb'.expandtabs(4) → 'a b' |
zfill(width) |
左侧填充零,保留符号 | '-42'.zfill(5) → '-0042' |
示例:
python
s = "Hi"
print(s.center(10, '*')) # ****Hi****
print(s.ljust(10, '-')) # Hi--------
print(s.rjust(10, '-')) # --------Hi
print("a\tb".expandtabs(4)) # a b
print("42".zfill(5)) # 00042
print("-42".zfill(5)) # -0042
拆分与连接方法
用于分割字符串或将序列合并为字符串。
方法 | 描述 | 示例 |
---|---|---|
lstrip() |
删除开头空格 | " hi".lstrip() → 'hi' |
rstrip() |
删除结尾空格 | "hi ".rstrip() → 'hi' |
strip() |
删除首尾空格 | " hi ".strip() → 'hi' |
split(sep=None, maxsplit=-1) |
按分隔符拆分 | "a,b,c".split(',') → ['a','b','c'] |
rsplit(sep=None, maxsplit=-1) |
从右边拆分 | "a,b,c".rsplit(',',1) → ['a,b','c'] |
splitlines(keepends=False) |
按行拆分 | "a\nb".splitlines() → ['a','b'] |
partition(sep) |
第一次出现分隔符分成三部分 | "a-b-c".partition('-') → ('a','-','b-c') |
rpartition(sep) |
从右边第一次分隔 | "a-b-c".rpartition('-') → ('a-b','-','c') |
join(iterable) |
将可迭代对象用字符串连接 | '-'.join(['a','b','c']) → 'a-b-c' |
removeprefix(prefix) |
移除开头指定前缀 | "HelloWorld".removeprefix("Hello") → 'World' |
removesuffix(suffix) |
移除结尾指定后缀 | "HelloWorld".removesuffix("World") → 'Hello' |
示例:
python
s = " apple, banana , cherry "
print(s.lstrip()) # "apple, banana , cherry "
print(s.rstrip()) # " apple, banana , cherry"
print(s.strip()) # "apple, banana , cherry"
print("a,b,c".split(",")) # ['a', 'b', 'c']
print("a,b,c".rsplit(",", 1)) # ['a,b', 'c']
print("a\nb\nc".splitlines()) # ['a', 'b', 'c']
print("a-b-c".partition("-")) # ('a', '-', 'b-c')
print("a-b-c".rpartition("-")) # ('a-b', '-', 'c')
print("-".join(["a","b","c"])) # a-b-c
print("HelloWorld".removeprefix("Hello")) # World
print("HelloWorld".removesuffix("World")) # Hello
布尔检查方法
返回 True
或 False
,用于检查字符串的内容或格式。
方法 | 描述 | 示例 |
---|---|---|
isalnum() |
是否字母数字 | "abc123".isalnum() → True |
isalpha() |
是否全字母 | "abc".isalpha() → True |
isdigit() |
是否全数字 | "123".isdigit() → True |
islower() |
是否全小写 | "abc".islower() → True |
isnumeric() |
是否全数字字符(UNICODE) | "²3".isnumeric() → True |
isspace() |
是否全空白字符 | " \t\n".isspace() → True |
istitle() |
是否标题化 | "Hello World".istitle() → True |
isupper() |
是否全大写 | "ABC".isupper() → True |
isascii() |
是否全 ASCII | "abc".isascii() → True |
isdecimal() |
是否十进制数字 | "123".isdecimal() → True |
isidentifier() |
是否合法标识符 | "var_1".isidentifier() → True |
isprintable() |
是否可打印 | "abc\n".isprintable() → False |
示例:
python
print("abc123".isalnum()) # True
print("abc".isalpha()) # True
print("123".isdigit()) # True
print("abc".islower()) # True
print("²3".isnumeric()) # True (支持 Unicode 数字)
print(" \t\n".isspace()) # True
print("Hello World".istitle()) # True
print("ABC".isupper()) # True
print("abc".isascii()) # True
print("123".isdecimal()) # True
print("var_1".isidentifier()) # True
print("abc\n".isprintable()) # False (\n 不可打印)
查找与替换方法
用于定位子字符串或替换字符串内容。
方法 | 描述 | 示例 |
---|---|---|
count(sub, start=0, end=len(s)) |
统计出现次数 | "aaabb".count("a") → 3 |
find(sub, start=0, end=len(s)) |
查找索引,找不到返回 -1 | "abc".find("b") → 1 |
index(sub, start=0, end=len(s)) |
查找索引,找不到报错 | "abc".index("b") → 1 |
replace(old, new, count=-1) |
替换子串 | "abcabc".replace("a","x",1) → 'xbcabc' |
rfind(sub, start=0, end=len(s)) |
从右查找,找不到返回 -1 | "abcabc".rfind("a") → 3 |
rindex(sub, start=0, end=len(s)) |
从右查找,找不到报错 | "abcabc".rindex("a") → 3 |
startswith(prefix, start=0, end=len(s)) |
是否以 prefix 开头 | "abc".startswith("a") → True |
endswith(suffix, start=0, end=len(s)) |
是否以 suffix 结尾 | "abc".endswith("c") → True |
示例:
python
s = "abcabc"
print(s.count("a")) # 2
print(s.find("b")) # 1
print(s.find("x")) # -1
print(s.index("b")) # 1
# print(s.index("x")) # 报错 ValueError
print(s.replace("a","x")) # xbcxbc
print(s.replace("a","x",1)) # xbcabc
print(s.rfind("a")) # 3
print(s.rindex("a")) # 3
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
翻译与字符映射方法
用于批量替换字符或删除字符。
方法 | 描述 | 示例 |
---|---|---|
str.maketrans(x, y, z=None) |
创建字符映射表,用于 translate | table = str.maketrans("abc","123") |
translate(table) |
使用映射表转换字符串 | "abc".translate(table) → '123' |
示例:
python
# 把 a->1, b->2, c->3
table = str.maketrans("abc", "123")
print("abcabc".translate(table)) # 123123
# 删除指定字符
table = str.maketrans("", "", "aeiou")
print("hello world".translate(table)) # hll wrld