Coniper.top代码笔记

代码笔记 / Python

11、字符串(str)

官方文档:
Python 文本序列类型 str

字符串是 Python 中最常用的数据类型之一。

姓名、密码、单词、句子、文件名、网址等文本数据,通常都会使用字符串保存。


1. 什么是字符串

字符串(string,简称 str)是由一串字符组成的序列。

Python 使用引号表示字符串,可以使用:

s1 = 'hello'
s2 = "Python"
s3 = '''三引号可以
直接换行书写'''

print(s1)
print(s2)
print(s3)

输出:

hello
Python
三引号可以
直接换行书写

单引号和双引号在大多数情况下没有区别:

name1 = 'Tom'
name2 = "Tom"

字符串中的内容既可以是英文字母,也可以是中文、数字、符号等:

s1 = "Python"
s2 = "你好"
s3 = "2026"
s4 = "A+B=C"

注意:

a = 123
b = "123"

虽然它们看起来相似,但类型不同:

print(type(a))   # <class 'int'>
print(type(b))   # <class 'str'>

2. 字符串也是序列

字符串属于序列(sequence)。

因此字符串和列表、元组一样,支持:

  • 索引、切片、遍历
  • len()
  • in、not in

例如:

text = "Python"

可以把它理解为:

P  y  t  h  o  n
0  1  2  3  4  5

也可以从右向左编号:

P   y   t   h   o   n
-6  -5  -4  -3  -2  -1

3. 字符串的索引

索引用来访问字符串中的某一个字符。

text = "Python"

print(text[0])    # P
print(text[1])    # y
print(text[2])    # t

也可以使用负数索引:

print(text[-1])   # n
print(text[-2])   # o
print(text[-3])   # h

其中:

text[0]

表示第一个字符。

而:

text[-1]

表示最后一个字符。

索引越界

如果索引超出范围:

text = "Python"

print(text[10])

程序会报错:

IndexError

4. 字符串切片

切片可以一次取出字符串中的一部分。

基本格式:

字符串[开始位置:结束位置:步长]

例如:

text = "Python"

print(text[0:4])   # Pyth
print(text[2:5])   # tho

切片遵循:

左闭右开

也就是说:

text[0:4]

会取得:

0 1 2 3

不会取得下标 4。


4.1 省略开始或结束位置

text = "Python"

print(text[2:])    # thon
print(text[:3])    # Pyt
print(text[:])     # Python

4.2 使用步长

text = "Python"

print(text[::2])   # Pto

表示:

每隔一个字符取一个。


4.3 倒序字符串

步长也可以是负数:

text = "Python"

print(text[::-1])

输出:

nohtyP

这是 Python 中非常常见的字符串反转方法。


5. 字符串的基本运算

5.1 获取长度

使用:

len()

例如:

s = "Python"

print(len(s))   # 6

中文字符同样按字符计算:

print(len("你好"))   # 2

5.2 字符串拼接

使用 +:

a = "Hello"
b = "Python"

print(a + " " + b)

输出:

Hello Python

5.3 字符串重复

使用 *:

print("Hi" * 3)

输出:

HiHiHi

5.4 判断内容是否存在

使用:

in

例如:

s = "I love Python"

print("Python" in s)   # True
print("Java" in s)     # False

也可以使用:

not in
print("Java" not in s)   # True

注意,in 判断的是子字符串是否存在:

print("yth" in "Python")   # True

6. 字符串是不可变对象

这是字符串非常重要的特点。

s = "Python"

s[0] = "J"

这样写会报错:

TypeError

因为字符串中的字符不能直接修改。

如果想得到:

Jython

可以重新生成一个字符串:

s = "Python"

s = "J" + s[1:]

print(s)

输出:

Jython

因此:

字符串的方法通常不会修改原字符串,而是返回一个新的字符串。

例如:

s = "python"

s.upper()

print(s)

输出仍然是:

python

如果希望保存转换后的结果,需要写:

s = s.upper()

print(s)

输出:

PYTHON

7. 字符串常用方法

字符串提供了大量方法。

基本形式:

字符串.方法()

例如:

s = "123"

print(s.isdigit())

输出:

True

下面按照用途分类学习。


7.1 大小写转换

常见方法:

方法

作用

upper()

转换为大写

lower()

转换为小写

title()

每个单词首字母大写

capitalize()

第一个字符大写,其余转小写

swapcase()

大小写互换

例如:

s = "hello PYTHON"

print(s.upper())
print(s.lower())
print(s.title())
print(s.capitalize())
print(s.swapcase())

输出:

HELLO PYTHON
hello python
Hello Python
Hello python
HELLO python



7.2 查找字符串

find()

查找子字符串第一次出现的位置:

s = "hello world"

print(s.find("lo"))

输出:

3

如果找不到:

print(s.find("abc"))

输出:

-1

因此可以这样判断:

s = "hello Python"

if s.find("Python") != -1:
    print("找到了")

不过仅仅判断是否存在时,更推荐:

if "Python" in s:
    print("找到了")

index()

index() 与 find() 类似:

s = "hello"

print(s.index("e"))   # 1

但如果找不到:

print(s.index("x"))

会直接报错:

ValueError

所以:

方法

找到

找不到

find()

返回位置

返回 -1

index()

返回位置

报错


count()

统计子字符串出现的次数:

s = "banana"

print(s.count("a"))

输出:

3

例如:

s = "abcabcabc"

print(s.count("abc"))   # 3

7.3 判断开头和结尾

startswith()

判断字符串是否以指定内容开头:

filename = "hello.py"

print(filename.startswith("hello"))

输出:

True

endswith()

判断字符串是否以指定内容结尾:

filename = "hello.py"

print(filename.endswith(".py"))

输出:

True

这在判断文件类型时非常方便:

filename = input()

if filename.endswith(".jpg"):
    print("这是一张 JPG 图片")

7.4 判断字符串内容:is...()

Python 中有一组以 is 开头的方法,用来判断字符串是否满足某种条件。

这些方法通常返回:

True

或:

False

isdigit()

判断字符串是否全部由数字字符组成。

print("123".isdigit())     # True
print("12a".isdigit())     # False
print("-123".isdigit())    # False
print("12.5".isdigit())    # False

注意:

"-123"
"12.5"

虽然表示数字,但其中含有:

-
.

因此 isdigit() 返回 False。


isalpha()

判断字符串是否全部由字母字符组成:

print("Python".isalpha())   # True
print("abc123".isalpha())   # False

Python 的字符串使用 Unicode,因此中文也属于文字字符:

print("你好".isalpha())   # True

isalnum()

判断字符串是否全部由:

字母或数字

组成。

print("abc123".isalnum())   # True
print("abc".isalnum())      # True
print("123".isalnum())      # True
print("abc_123".isalnum())  # False

因为 _ 既不是字母,也不是数字。


isspace()

判断是否全部由空白字符组成:

print("   ".isspace())      # True
print("\t\n".isspace())     # True
print(" a ".isspace())      # False

空白字符不仅包括空格,还包括:

\t    制表符
\n    换行符

islower() 和 isupper()

print("python".islower())   # True
print("PYTHON".isupper())   # True

istitle()

判断字符串是否符合标题格式:

print("Hello World".istitle())   # True
print("hello world".istitle())   # False

7.5 isdecimal、isdigit、isnumeric 的区别

这三个方法都与数字有关,但判断范围不同。

一般可以理解为:

isdecimal()
    ↓
isdigit()
    ↓
isnumeric()

范围越来越宽。

普通数字

s = "123"

print(s.isdecimal())   # True
print(s.isdigit())     # True
print(s.isnumeric())   # True

上标数字

s = "²"

print(s.isdecimal())   # False
print(s.isdigit())     # True
print(s.isnumeric())   # True

某些其他数字字符

s = "Ⅻ"

print(s.isdecimal())   # False
print(s.isdigit())     # False
print(s.isnumeric())   # True

初学阶段可以这样记:

方法

范围

isdecimal()

最严格

isdigit()

常用数字判断

isnumeric()

范围最广

在普通编程题中:

isdigit()

使用得最多。


7.6 替换字符串

replace()

基本格式:

字符串.replace(旧内容, 新内容)

例如:

s = "我喜欢Python,Python很好玩"

print(s.replace("Python", "C++"))

输出:

我喜欢C++,C++很好玩

还可以限制替换次数:

s = "Python Python Python"

print(s.replace("Python", "C++", 1))

输出:

C++ Python Python

再次注意:

replace()

不会修改原字符串。

例如:

s = "abc"

s.replace("a", "x")

print(s)

仍然输出:

abc

应该写成:

s = s.replace("a", "x")

7.7 清理字符串两端

strip()

去掉字符串两端的空白字符:

s = "   hello   "

print(s.strip())

得到:

hello

lstrip()

只处理左边:

print("   hello   ".lstrip())

rstrip()

只处理右边:

print("   hello   ".rstrip())

指定字符

还可以指定要清理的字符:

s = "...hello..."

print(s.strip("."))

输出:

hello

注意:

strip() 处理的是两端的字符集合,不是删除字符串中间的内容。

例如:

s = "abcHelloabc"

print(s.strip("abc"))

结果:

Hello

但:

s = "abcHelloabcWorld"

print(s.strip("abc"))

并不会删除中间的:

abc

7.8 字符串拆分

split()

split() 可以把一个字符串拆成多个部分,并返回列表。

例如:

s = "苹果,香蕉,西瓜"

fruits = s.split(",")

print(fruits)

输出:

['苹果', '香蕉', '西瓜']

默认按空白拆分

如果不写参数:

s = "Python  is   fun"

print(s.split())

输出:

['Python', 'is', 'fun']

连续空白会自动处理。

它还可以处理:

"Python\nis\tfun".split()

限制拆分次数

s = "a,b,c,d"

print(s.split(",", 2))

输出:

['a', 'b', 'c,d']

7.9 从右侧拆分

使用:

rsplit()

例如:

filename = "photo.backup.jpg"

print(filename.rsplit(".", 1))

输出:

['photo.backup', 'jpg']

在处理文件扩展名时非常实用。


7.10 字符串拼接

join()

join() 可以把多个字符串连接起来。

例如:

words = ["Python", "is", "fun"]

print(" ".join(words))

输出:

Python is fun

使用:

",".join(["苹果", "香蕉", "西瓜"])

得到:

苹果,香蕉,西瓜

可以把它理解成:

"连接符".join(字符串序列)

例如:

"-".join(["2026", "09", "25"])

得到:

2026-09-25

7.11 partition()

partition() 会按照指定内容把字符串分成三部分:

s = "name=Tom"

print(s.partition("="))

结果:

('name', '=', 'Tom')

返回的是一个元组:

分隔符左边
分隔符本身
分隔符右边

还有:

rpartition()

表示从右侧寻找分隔符。


7.12 删除指定前缀和后缀

removeprefix()

url = "https://example.com"

print(url.removeprefix("https://"))

输出:

example.com

只有匹配成功才会移除。


removesuffix()

filename = "hello.py"

print(filename.removesuffix(".py"))

输出:

hello

7.13 补齐与对齐

zfill()

在左侧补 0:

print("12".zfill(5))

输出:

00012

例如生成编号:

for i in range(1, 6):
    print(str(i).zfill(3))

输出:

001
002
003
004
005

center()

居中:

print("Python".center(10, "-"))

例如得到:

--Python--

ljust() 和 rjust()

print("abc".ljust(6, "-"))
print("abc".rjust(6, "-"))

输出:

abc---
---abc

8. 字符串遍历

因为字符串是序列,所以可以直接使用 for 遍历。

s = "Python"

for ch in s:
    print(ch, end=" ")

输出:

P y t h o n

这里:

ch

每次代表字符串中的一个字符。


8.1 统计字符数量

例如统计数字字符:

s = "abc123xyz45"

cnt = 0

for ch in s:
    if ch.isdigit():
        cnt += 1

print(cnt)

输出:

5

8.2 分类统计

s = input()

letters = 0
digits = 0

for ch in s:
    if ch.isalpha():
        letters += 1
    elif ch.isdigit():
        digits += 1

print("字母:", letters)
print("数字:", digits)

这也是 isalpha()、isdigit() 在编程题中的典型用法。


9. f-string 格式化

Python 3.6+ 支持 f-string。

基本格式:

f"文本{变量}"

例如:

name = "小明"
age = 10

print(f"大家好,我叫{name},今年{age}岁。")

输出:

大家好,我叫小明,今年10岁。

9.1 可以直接写表达式

a = 10
b = 20

print(f"{a} + {b} = {a + b}")

输出:

10 + 20 = 30

9.2 控制小数位数

pi = 3.1415926

print(f"{pi:.2f}")

输出:

3.14

其中:

.2f

表示保留两位小数。


10. 常见易错点

10.1 字符串不能直接修改

错误:

s = "abc"
s[0] = "A"

正确:

s = "A" + s[1:]

10.2 字符串方法通常返回新字符串

错误:

s = "abc"

s.upper()

print(s)

结果仍然是:

abc

正确:

s = s.upper()

10.3 split() 返回列表

s = "a,b,c"

result = s.split(",")

print(type(result))

输出:

<class 'list'>

10.4 join() 的调用方向

错误理解:

list.join(",")

正确写法:

",".join(["a", "b", "c"])

可以记成:

用什么连接,就让什么调用 join。


10.5 strip() 不会删除中间内容

s = "  hello world  "

print(s.strip())

只会处理两端:

hello world

不会删除中间的空格。


10.6 isdigit() 不能直接判断负数和小数

print("-12".isdigit())    # False
print("3.14".isdigit())   # False

因为:

-
.

都不是数字字符。


11. 字符串常用方法速查

S 级:必会

这部分建议熟练掌握。

方法 / 操作

功能

示例

len(s)

获取字符串长度

len("abc") → 3

s[a:b:c]

字符串切片

s[::-1]

in

判断子字符串是否存在

"ab" in "xxabyy"

s.strip()

清理两端空白

" a ".strip()

s.split(sep)

拆分字符串

"a,b".split(",")

sep.join(seq)

拼接字符串

",".join(["a","b"])

s.replace(a,b)

替换内容

"a-a".replace("-", "+")

s.find(sub)

查找位置

"abc".find("b")

s.count(sub)

统计出现次数

"banana".count("a")

s.startswith(x)

判断开头

"abc".startswith("a")

s.endswith(x)

判断结尾

"a.py".endswith(".py")

s.lower()

转小写

"Ab".lower()

s.upper()

转大写

"Ab".upper()

s.isdigit()

是否都是数字字符

"123".isdigit()

s.isalpha()

是否都是字母字符

"abc".isalpha()

s.isalnum()

是否都是字母或数字

"a1".isalnum()


12. A 级:常用

方法

功能

index()

查找位置,找不到报错

title()

每个单词首字母大写

capitalize()

首字符大写

swapcase()

大小写互换

lstrip()

清理左侧

rstrip()

清理右侧

rsplit()

从右拆分

partition()

分成左、分隔符、右三部分

rpartition()

从右寻找分隔符

find(sub,start,end)

指定范围查找

count(sub,start,end)

指定范围统计


13. B 级:了解并会查询

方法

功能

islower()

是否全部为小写

isupper()

是否全部为大写

isspace()

是否全部为空白字符

istitle()

是否符合标题格式

isdecimal()

判断十进制数字字符

isnumeric()

更宽泛的数字判断

zfill()

左侧补零

center()

居中填充

ljust()

左对齐

rjust()

右对齐

removeprefix()

删除指定前缀

removesuffix()

删除指定后缀

expandtabs()

展开制表符

translate()

字符映射替换

str.maketrans()

创建字符映射表


14. C 级:知道存在即可

方法

作用

casefold()

更彻底的大小写标准化

encode()

将字符串编码为 bytes

format()

字符串格式化

format_map()

使用映射进行格式化

现阶段遇到时查文档即可,不需要专门记忆。


15. 如何查看字符串有哪些方法

Python 可以直接查看某个类型支持的方法:

print(dir(str))

也可以:

s = "hello"

print(dir(s))

如果想查看某个方法的使用说明:

help(str.isdigit)

例如:

help(str.split)

因此实际编程中:

不需要死记所有方法,重要的是知道有哪些常见工具,并知道如何查询。


16. 综合示例

例 1:判断输入是否全部为数字

s = input("请输入内容:")

if s.isdigit():
    print("全部是数字")
else:
    print("不全是数字")

例 2:统计字母和数字

s = input()

letters = 0
digits = 0

for ch in s:
    if ch.isalpha():
        letters += 1
    elif ch.isdigit():
        digits += 1

print("字母数量:", letters)
print("数字数量:", digits)

例 3:统计某个字符出现次数

s = input()
ch = input()

print(s.count(ch))

例 4:处理逗号分隔的数据

输入:

Tom,12,98

程序:

s = input()

data = s.split(",")

name = data[0]
age = data[1]
score = data[2]

print(name)
print(age)
print(score)

例 5:判断文件类型

filename = input()

if filename.endswith(".py"):
    print("Python 文件")
elif filename.endswith(".cpp"):
    print("C++ 文件")
else:
    print("其他文件")

17. 小练习

1. 字符串切片

给定字符串:

abcdefg

请使用切片操作取出其中的:

bcd

2. 判断是否为数字字符串

输入一个字符串,判断它是否全部由数字字符组成。

例如:

2026

应判断为数字字符串。


3. 字符串替换

给定字符串:

I love Python

请将其中的:

Python

替换为:

C++

并输出替换后的结果。


4. 字符串拆分

给定字符串:

苹果,香蕉,葡萄

请以逗号 , 为分隔符,将字符串拆分成一个列表,并输出结果。


5. 字符串拼接

给定列表:

["2026", "09", "25"]

请使用字符串方法将它拼接成:

2026-09-25

6. 统计数字字符数量

输入一个字符串,统计其中数字字符的数量。

例如输入:

abc123xyz45

输出:

5

7. 字符分类统计

输入一个字符串,分别统计其中:

  • 字母字符的数量
  • 数字字符的数量
  • 其他字符的数量

最后分别输出三类字符的数量。


8. 判断 Python 文件

输入一个文件名,判断它是否是 Python 文件。

如果文件名以:

.py

结尾,则输出:

是Python文件

否则输出:

不是Python文件

9. 判断回文字符串

输入一个字符串,判断它是否是回文字符串。

回文字符串是指:

正着读和倒着读完全相同的字符串。

例如:

level

是回文字符串,而:

python

不是回文字符串。


10. 拆分学生信息

输入一行学生信息,格式如下:

Tom,12,98

其中依次表示:

姓名,年龄,成绩

请将字符串拆分后,分别输出姓名、年龄和成绩。