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"
print(text[0]) print(text[1]) print(text[5])
print(text[-1]) print(text[-2]) print(text[-6])
|
切片
1 2 3 4 5 6 7 8 9 10
| text = "Python"
print(text[0:2]) print(text[2:5]) print(text[:3]) print(text[3:]) print(text[::2]) print(text[::-1]) print(text[-3:])
|
6.3 字符串常用方法
大小写转换
1 2 3 4 5 6 7
| text = "Hello World"
print(text.upper()) print(text.lower()) print(text.capitalize()) print(text.title()) print(text.swapcase())
|
查找与替换
1 2 3 4 5 6 7 8 9 10
| text = "Hello World"
print(text.find("World")) print(text.index("World")) print(text.count("l"))
print(text.replace("World", "Python")) print(text.replace("l", "L", 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)
sentence = "Hello World Python" words = sentence.split() print(words)
result = "-".join(fruits) print(result)
result = " ".join(words) print(result)
|
去除空白
1 2 3 4 5 6 7 8 9
| text = " Hello World "
print(text.strip()) print(text.lstrip()) print(text.rstrip())
text = "---Hello---" print(text.strip("-"))
|
6.4 字符串判断方法
1 2 3 4 5 6 7 8 9 10
| text = "Hello123"
print(text.isalpha()) print(text.isdigit()) print(text.isalnum()) print(text.islower()) print(text.isupper()) print(text.istitle()) print(text.startswith("He")) print(text.endswith("23"))
|
实际应用:输入验证
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}") print(f"π 保留四位小数: {pi:.4f}")
text = "Python" print(f"左对齐: |{text:<10}|") print(f"右对齐: |{text:>10}|") print(f"居中: |{text:^10}|") print(f"填充: |{text:*^10}|")
|
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)) print("百分比: {:.1%}".format(0.75))
|
% 格式化(旧式,不推荐)
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)
decoded = encoded.decode("utf-8") print(decoded)
|
6.7 字符串不可变性
Python 字符串是不可变的,不能直接修改字符。
1 2 3 4 5 6 7 8 9 10 11 12
| text = "Hello"
text = "h" + text[1:] print(text)
text = text.replace("h", "H") print(text)
|
6.8 实用技巧
重复字符串
1 2
| print("-" * 20) print("Ha" * 3)
|
成员检查
1 2 3
| text = "Hello World" print("Hello" in text) print("Python" not in text)
|
多行字符串处理
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()
- 字符串不可变,修改需创建新字符串
练习题
- 输入一个字符串,统计其中元音字母(a, e, i, o, u)的数量
- 输入一个句子,将每个单词首字母大写后输出
- 输入一个邮箱地址,验证是否包含 “@” 和 “.”
- 以下代码输出什么?
1 2 3 4
| text = "Python" print(text[1:4]) print(text[::-1]) print(text.upper().lower())
|