Python 字符串操作

6.1 字符串创建

Python 字符串是不可变的字符序列,可以用单引号、双引号或三引号创建。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 单引号
s1 = 'Hello'

# 双引号
s2 = "World"

# 三引号(多行字符串)
s3 = """这是一段
多行文本"""

# 空字符串
empty = ""

# 包含引号的字符串
quote1 = "He said 'Hello'"
quote2 = 'She said "Hi"'
quote3 = """包含'单引号'和"双引号"""

6.2 字符串索引与切片

字符串支持索引访问和切片操作。

索引

1
2
3
4
5
6
7
8
9
10
11
text = "Python"

# 正向索引(从 0 开始)
print(text[0]) # P
print(text[1]) # y
print(text[5]) # n

# 负向索引(从 -1 开始)
print(text[-1]) # n
print(text[-2]) # o
print(text[-6]) # P

切片

1
2
3
4
5
6
7
8
9
10
text = "Python"

# 语法: [start:end:step]
print(text[0:2]) # Py(包含 0,不包含 2)
print(text[2:5]) # tho
print(text[:3]) # Pyt(省略 start,从头开始)
print(text[3:]) # hon(省略 end,到末尾)
print(text[::2]) # Pto(步长为 2)
print(text[::-1]) # nohtyP(反转字符串)
print(text[-3:]) # hon(最后 3 个字符)

6.3 字符串常用方法

大小写转换

1
2
3
4
5
6
7
text = "Hello World"

print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.capitalize()) # Hello world(首字母大写)
print(text.title()) # Hello World(每个单词首字母大写)
print(text.swapcase()) # hELLO wORLD(大小写互换)

查找与替换

1
2
3
4
5
6
7
8
9
10
text = "Hello World"

# 查找
print(text.find("World")) # 6(返回索引,未找到返回 -1)
print(text.index("World")) # 6(返回索引,未找到抛异常)
print(text.count("l")) # 3(出现次数)

# 替换
print(text.replace("World", "Python")) # Hello Python
print(text.replace("l", "L", 1)) # HeLlo World(只替换 1 次)

分割与连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
text = "apple,banana,orange"

# 分割
fruits = text.split(",")
print(fruits) # ['apple', 'banana', 'orange']

# 按空格分割(默认)
sentence = "Hello World Python"
words = sentence.split()
print(words) # ['Hello', 'World', 'Python']

# 连接
result = "-".join(fruits)
print(result) # apple-banana-orange

result = " ".join(words)
print(result) # Hello World Python

去除空白

1
2
3
4
5
6
7
8
9
text = "  Hello World  "

print(text.strip()) # "Hello World"(去除两端空白)
print(text.lstrip()) # "Hello World "(去除左侧)
print(text.rstrip()) # " Hello World"(去除右侧)

# 去除指定字符
text = "---Hello---"
print(text.strip("-")) # Hello

6.4 字符串判断方法

1
2
3
4
5
6
7
8
9
10
text = "Hello123"

print(text.isalpha()) # False(包含数字)
print(text.isdigit()) # False(包含字母)
print(text.isalnum()) # True(字母或数字)
print(text.islower()) # False(不全小写)
print(text.isupper()) # False(不全大写)
print(text.istitle()) # True(标题格式)
print(text.startswith("He")) # True
print(text.endswith("23")) # True

实际应用:输入验证

1
2
3
4
5
6
7
while True:
username = input("请输入用户名: ")
if username.isalnum() and 4 <= len(username) <= 16:
print("用户名有效")
break
else:
print("用户名必须是 4-16 位字母或数字")

6.5 字符串格式化

f-string(推荐,Python 3.6+)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
name = "Alice"
age = 25

# 基本用法
print(f"姓名: {name}, 年龄: {age}")

# 表达式
print(f"明年年龄: {age + 1}")

# 格式化数字
pi = 3.1415926
print(f"π 保留两位小数: {pi:.2f}") # 3.14
print(f"π 保留四位小数: {pi:.4f}") # 3.1416

# 对齐
text = "Python"
print(f"左对齐: |{text:<10}|") # |Python |
print(f"右对齐: |{text:>10}|") # | Python|
print(f"居中: |{text:^10}|") # | Python |
print(f"填充: |{text:*^10}|") # **Python**

format() 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
name = "Bob"
age = 30

# 位置参数
print("姓名: {}, 年龄: {}".format(name, age))

# 索引参数
print("姓名: {0}, 年龄: {1}, 姓名: {0}".format(name, age))

# 关键字参数
print("姓名: {n}, 年龄: {a}".format(n=name, a=age))

# 格式化数字
print("价格: {:.2f}".format(19.9)) # 19.90
print("百分比: {:.1%}".format(0.75)) # 75.0%

% 格式化(旧式,不推荐)

1
2
3
4
5
name = "Charlie"
age = 35

print("姓名: %s, 年龄: %d" % (name, age))
print("价格: %.2f" % 19.9)

6.6 字符串编码

1
2
3
4
5
6
7
8
9
text = "你好 Python"

# 编码(字符串 -> 字节)
encoded = text.encode("utf-8")
print(encoded) # b'\xe4\xbd\xa0\xe5\xa5\xbd Python'

# 解码(字节 -> 字符串)
decoded = encoded.decode("utf-8")
print(decoded) # 你好 Python

6.7 字符串不可变性

Python 字符串是不可变的,不能直接修改字符。

1
2
3
4
5
6
7
8
9
10
11
12
text = "Hello"

# 错误:不能修改字符
# text[0] = "h" # TypeError

# 正确:创建新字符串
text = "h" + text[1:]
print(text) # hello

# 使用 replace
text = text.replace("h", "H")
print(text) # Hello

6.8 实用技巧

重复字符串

1
2
print("-" * 20)  # --------------------
print("Ha" * 3) # HaHaHa

成员检查

1
2
3
text = "Hello World"
print("Hello" in text) # True
print("Python" not in text) # True

多行字符串处理

1
2
3
4
5
6
7
8
9
10
text = """
第一行
第二行
第三行
"""

# 去除首尾空行并按行分割
lines = text.strip().split("\n")
for line in lines:
print(f"行内容: {line}")

6.9 本章小结

  • 字符串是不可变的字符序列
  • 索引和切片用于访问和提取子串
  • 常用方法:upper()lower()find()replace()split()join()
  • f-string 是最推荐的格式化方式
  • 字符串编码使用 encode()decode()
  • 字符串不可变,修改需创建新字符串

练习题

  1. 输入一个字符串,统计其中元音字母(a, e, i, o, u)的数量
  2. 输入一个句子,将每个单词首字母大写后输出
  3. 输入一个邮箱地址,验证是否包含 “@” 和 “.”
  4. 以下代码输出什么?
    1
    2
    3
    4
    text = "Python"
    print(text[1:4])
    print(text[::-1])
    print(text.upper().lower())
ByteFisher
分享编程技术 · 记录钓鱼乐趣
扫码关注
▸ 扫码关注 ◂
Python基础教程 系列
第 6/20 篇
分享: