1. 字符串的创建
在 Python 中,可以使用单引号、双引号、三引号来创建字符串,三引号还可用于创建多行字符串。
# 单引号创建字符串
single_quoted_str = 'Hello, Python!'
print(single_quoted_str)
# 双引号创建字符串
double_quoted_str = "Welcome to Python world"
print(double_quoted_str)
# 三引号创建多行字符串
triple_quoted_str = '''This is a
multi - line
string example.'''
print(triple_quoted_str)
2. 字符串的访问
可以通过索引访问字符串中的单个字符,也可以使用切片获取子字符串。索引从 0 开始,支持负数索引,负数索引表示从字符串末尾开始计数。
str_example = "Python Programming"
# 访问单个字符
print(str_example[0]) # 输出 'P'
print(str_example[-1]) # 输出 'g'
# 切片操作 [start:stop:step]
print(str_example[0:6]) # 输出 'Python'
print(str_example[7:]) # 输出 'Programming'
print(str_example[::-1]) # 反转字符串,输出 'gnimmargorP nohtyP'
3. 字符串的修改
在 Python 中,字符串是不可变对象,不能直接修改字符串中的某个字符,但可以通过拼接、替换等方式得到新的字符串。
original_str = "Hello"
# 拼接字符串
new_str = original_str + " World"
print(new_str)
# 替换字符串
replaced_str = new_str.replace("World", "Python")
print(replaced_str)
4. 字符串的查询
可以使用多种方法来查询字符串中的子字符串。
search_str = "Python is a great programming language"
# find() 方法:返回子字符串首次出现的索引,若未找到则返回 -1
print(search_str.find("great")) # 输出 10
# index() 方法:返回子字符串首次出现的索引,若未找到则抛出 ValueError 异常
print(search_str.index("programming")) # 输出 16
# count() 方法:统计子字符串出现的次数
print(search_str.count("a")) # 输出 3
5. 字符串的格式化
Python 提供了多种字符串格式化的方式,包括旧式的 % 格式化、format() 方法和 f - string(Python 3.6 及以上版本支持)。
name = "Alice"
age = 28
# % 格式化
old_style = "My name is %s and I am %d years old." % (name, age)
print(old_style)
# format() 方法
format_method = "My name is {} and I am {} years old.".format(name, age)
print(format_method)
# f - string
f_string = f"My name is {name} and I am {age} years old."
print(f_string)
6. 字符串的大小写转换
case_str = "Hello, Python"
# upper() 方法:将字符串转换为大写
print(case_str.upper()) # 输出 'HELLO, PYTHON'
# lower() 方法:将字符串转换为小写
print(case_str.lower()) # 输出 'hello, python'
# capitalize() 方法:将字符串的首字母大写
print(case_str.capitalize()) # 输出 'Hello, python'
# title() 方法:将字符串中每个单词的首字母大写
print(case_str.title()) # 输出 'Hello, Python'
# swapcase() 方法:将字符串中的大小写字母互换
print(case_str.swapcase()) # 输出 'hELLO, pYTHON'
7. 字符串的去除空白
space_str = " Hello, Python "
# strip() 方法:去除字符串两端的空白字符
print(space_str.strip()) # 输出 'Hello, Python'
# lstrip() 方法:去除字符串左端的空白字符
print(space_str.lstrip()) # 输出 'Hello, Python '
# rstrip() 方法:去除字符串右端的空白字符
print(space_str.rstrip()) # 输出 ' Hello, Python'
8. 字符串的分割与连接
split_str = "apple,banana,orange"
# split() 方法:将字符串按指定分隔符分割成列表
fruits = split_str.split(",")
print(fruits) # 输出 ['apple', 'banana', 'orange']
# join() 方法:将列表中的元素用指定字符串连接成一个新的字符串
joined_str = "-".join(fruits)
print(joined_str) # 输出 'apple-banana-orange'
9. 字符串的判断
可以使用一些方法来判断字符串的特性。
judge_str1 = "12345"
judge_str2 = "Hello"
judge_str3 = "Hello123"
judge_str4 = " "
# isdigit() 方法:判断字符串是否全由数字组成
print(judge_str1.isdigit()) # 输出 True
# isalpha() 方法:判断字符串是否全由字母组成
print(judge_str2.isalpha()) # 输出 True
# isalnum() 方法:判断字符串是否全由字母或数字组成
print(judge_str3.isalnum()) # 输出 True
# isspace() 方法:判断字符串是否全由空白字符组成
print(judge_str4.isspace()) # 输出 True
10. 字符串的填充
fill_str = "42"
# zfill() 方法:用 0 在字符串左侧填充到指定长度
print(fill_str.zfill(5)) # 输出 '00042'
# rjust() 方法:右对齐字符串,用指定字符在左侧填充到指定长度
print(fill_str.rjust(5, '*')) # 输出 '***42'
# ljust() 方法:左对齐字符串,用指定字符在右侧填充到指定长度
print(fill_str.ljust(5, '*')) # 输出 '42***'
# center() 方法:居中对齐字符串,用指定字符在两侧填充到指定长度
print(fill_str.center(5, '*')) # 输出 '*42**'
11. 字符串的编码与解码
encode_str = "你好,世界"
# encode() 方法:将字符串编码为指定格式的字节对象
encoded_bytes = encode_str.encode('utf-8')
print(encoded_bytes)
# decode() 方法:将字节对象解码为字符串
decoded_str = encoded_bytes.decode('utf-8')
print(decoded_str)
12. 字符串的乘法
可以使用乘法运算符将字符串重复多次。
repeat_str = "Hi"
print(repeat_str * 3) # 输出 'HiHiHi'
13. 字符串的比较
可以使用比较运算符(如 <、>、== 等)对字符串进行比较,比较是基于字符的 Unicode 码点。
compare_str1 = "apple"
compare_str2 = "banana"
print(compare_str1 < compare_str2) # 输出 True
14. 字符串的转义字符
转义字符用于表示一些特殊字符,如换行符、制表符等。
# 换行符 \n
print("Hello\nWorld")
# 制表符 \t
print("Name\tAge")
print("Alice\t25")
# 反斜杠 \\
print("C:\\Users\\Alice")
# 单引号 \'
print('It\'s a beautiful day')
# 双引号 \"
print("He said, \"Hello!\"")
以下继续为你补充更多关于 Python 字符串操作的内容及代码示例:
15. 字符串的正则表达式操作
正则表达式是用于匹配、查找和替换字符串模式的强大工具,Python 中通过 re 模块来支持正则表达式操作。
import re
# 查找匹配的字符串
text = "The price of the book is $20 and the pen is $5."
# 查找所有的美元价格
prices = re.findall(r'\$\d+', text)
print(prices) # 输出: ['$20', '$5']
# 替换匹配的字符串
new_text = re.sub(r'\$\d+', 'N/A', text)
print(new_text) # 输出: 'The price of the book is N/A and the pen is N/A.'
# 检查字符串是否匹配某个模式
pattern = r'^The.*book'
if re.match(pattern, text):
print("The text matches the pattern.")
else:
print("The text does not match the pattern.")
16. 字符串的startswith()和endswith()方法
用于检查字符串是否以指定的前缀或后缀开始或结束。
str_data = "Python Programming"
# startswith() 方法
if str_data.startswith("Python"):
print("The string starts with 'Python'.")
else:
print("The string does not start with 'Python'.")
# endswith() 方法
if str_data.endswith("Programming"):
print("The string ends with 'Programming'.")
else:
print("The string does not end with 'Programming'.")
17. 字符串的partition()和rpartition()方法
partition() 方法从左到右搜索指定的分隔符,并将字符串分割为三部分(分隔符前的部分、分隔符本身、分隔符后的部分);rpartition() 方法则是从右到左进行相同的操作。
data_str = "apple,banana,orange"
# partition() 方法
result1 = data_str.partition(',')
print(result1) # 输出: ('apple', ',', 'banana,orange')
# rpartition() 方法
result2 = data_str.rpartition(',')
print(result2) # 输出: ('apple,banana', ',', 'orange')
18. 字符串的maketrans()和translate()方法
maketrans() 方法用于创建字符映射表,translate() 方法用于根据这个映射表对字符串进行字符替换。
# 创建映射表,将 'a' 替换为 'X','b' 替换为 'Y'
table = str.maketrans('ab', 'XY')
text = "abcdef"
new_text = text.translate(table)
print(new_text) # 输出: 'XYcdef'
19. 字符串的迭代
可以使用 for 循环对字符串进行迭代,依次访问每个字符。
str_iter = "Hello"
for char in str_iter:
print(char)
20. 字符串的长度计算
使用 len() 函数可以获取字符串的长度,即字符串中字符的数量。
str_len = "Python"
print(len(str_len)) # 输出: 6
21. 字符串的成员测试
可以使用 in 和 not in 运算符来测试一个子字符串是否存在于另一个字符串中。
str_test = "Hello, World"
if "World" in str_test:
print("'World' is in the string.")
else:
print("'World' is not in the string.")
if "Python" not in str_test:
print("'Python' is not in the string.")
else:
print("'Python' is in the string.")
22. 字符串的排序
如果需要对字符串中的字符进行排序,可以先将字符串转换为列表,对列表排序后再转换回字符串。
str_sort = "cbad"
sorted_chars = sorted(str_sort)
sorted_str = ''.join(sorted_chars)
print(sorted_str) # 输出: 'abcd'
23. 字符串的扩展切片
扩展切片的语法是 [start:stop:step],除了可以用于反转字符串,还可以以指定的步长选取字符。
str_ext_slice = "abcdefg"
# 每隔一个字符选取
print(str_ext_slice[::2]) # 输出: 'aceg'
24. 字符串的格式化进阶:对齐和精度控制
在使用 format() 方法或 f - string 时,可以进行更复杂的格式化,如对齐和精度控制。
# format() 方法的对齐和精度控制
num = 3.14159
print("{:^10.2f}".format(num)) # 居中对齐,总宽度为 10,保留 2 位小数
# f - string 的对齐和精度控制
print(f"{num:>10.2f}") # 右对齐,总宽度为 10,保留 2 位小数
25. 使用splitlines()方法分割多行字符串
splitlines() 方法用于将多行字符串按行分割成一个字符串列表,换行符可以是 \n、\r、\r\n 等。
multi_line_str = "Line 1\nLine 2\rLine 3\r\nLine 4"
lines = multi_line_str.splitlines()
print(lines)
26. 检查字符串是否只包含 ASCII 字符
可以通过遍历字符串中的每个字符,使用 ord() 函数获取字符的 Unicode 编码,判断是否在 ASCII 编码范围内(0 - 127)。
def is_ascii(s):
return all(ord(c) < 128 for c in s)
str1 = "Hello World"
str2 = "你好,世界"
print(is_ascii(str1)) # 输出: True
print(is_ascii(str2)) # 输出: False
27. 使用casefold()方法进行不区分大小写的字符串比较
casefold() 方法比 lower() 更强大,尤其适用于处理一些特殊语言的字符,用于进行更全面的不区分大小写的字符串比较。
str_a = "Stra?e"
str_b = "strasse"
print(str_a.casefold() == str_b.casefold()) # 输出: True
28. 字符串的替换计数
replace() 方法可以接受第三个参数,用于指定替换的最大次数。
text = "apple apple apple"
new_text = text.replace("apple", "banana", 2)
print(new_text) # 输出: "banana banana apple"
29. 字符串的条件替换
结合 if - else 语句和字符串操作,可以实现根据条件进行字符串替换。
text = "The number is 10"
new_text = text.replace("10", "twenty") if "10" in text else text
print(new_text) # 输出: "The number is twenty"
30. 从字符串中提取数字
可以使用正则表达式结合 re.findall() 方法从字符串中提取所有数字。
import re
text = "There are 3 apples and 5 bananas"
numbers = re.findall(r'\d+', text)
print(numbers) # 输出: ['3', '5']
31. 字符串的编码检测
如果不确定字符串的编码,可以使用 chardet 库来检测。
import chardet
byte_str = b'\xd6\xd0\xb9\xfa' # 假设这是一个字节字符串
result = chardet.detect(byte_str)
print(result) # 输出包含编码信息的字典,如 {'encoding': 'GB2312', 'confidence': 0.99, 'language': 'Chinese'}
32. 字符串的填充对齐进阶
在 format() 或 f - string 中,可以使用自定义字符进行填充对齐。
num = 123
print("{:*>10}".format(num)) # 使用 * 进行右对齐填充,总宽度为 10
print(f"{num:_<10}") # 使用 _ 进行左对齐填充,总宽度为 10
33. 字符串的重复拼接优化
当需要多次重复拼接字符串时,使用 join() 方法比 + 运算符更高效,尤其是在拼接大量字符串时。
str_list = ["Hello"] * 1000
# 高效拼接
efficient_str = ''.join(str_list)
34. 字符串的部分替换
可以通过切片和拼接实现字符串的部分替换。
original_str = "abcdef"
new_str = original_str[:2] + "XX" + original_str[4:]
print(new_str) # 输出: "abXXef"
35. 字符串的前后缀去除
可以使用切片和 startswith()、endswith() 方法去除字符串的指定前后缀。
str_with_prefix = "prefix_hello"
if str_with_prefix.startswith("prefix_"):
new_str = str_with_prefix[len("prefix_"):]
print(new_str) # 输出: "hello"
str_with_suffix = "world_suffix"
if str_with_suffix.endswith("_suffix"):
new_str = str_with_suffix[:-len("_suffix")]
print(new_str) # 输出: "world"