Python 字符串
字符串是 Python 中最常用的数据类型之一。在 Python 中,字符串可以使用单引号(')或双引号(")来创建。
1. 字符串的基本操作
1.1 创建字符串
# 使用单引号
str1 = 'Hello World'
# 使用双引号
str2 = "Python Programming"
# 使用三引号(可以包含多行)
str3 = '''这是一个
多行字符串
示例'''
1.2 字符串的访问
text = "Python"
# 访问单个字符
print(text[0]) # 输出: P
print(text[-1]) # 输出: n
# 字符串切片
print(text[0:3]) # 输出: Pyt
2. 字符串的常用方法
2.1 字符串修改
text = "hello world"
# 转换为大写
print(text.upper()) # 输出: HELLO WORLD
# 转换为小写
print(text.lower()) # 输出: hello world
# 首字母大写
print(text.capitalize()) # 输出: Hello world
# 每个单词首字母大写
print(text.title()) # 输出: Hello World
2.2 字符串查找和替换
text = "Python is awesome"
# 查找子字符串
print(text.find("is")) # 输出: 7
print(text.count("o")) # 输出: 2
# 替换字符串
print(text.replace("awesome", "great")) # 输出: Python is great
2.3 字符串分割和连接
# 分割字符串
text = "Python,Java,C++"
languages = text.split(",") # 输出: ['Python', 'Java', 'C++']
# 连接字符串
words = ['Hello', 'World']
sentence = " ".join(words) # 输出: Hello World
3. 字符串格式化
3.1 f-string(推荐使用)
name = "Alice"
age = 25
print(f"{name} is {age} years old")
3.2 format() 方法
name = "Bob"
age = 30
print("{} is {} years old".format(name, age))
3.3 % 操作符
name = "Charlie"
age = 35
print("%s is %d years old" % (name, age))
4. 字符串的常用操作符
# 连接操作符 +
str1 = "Hello"
str2 = "World"
print(str1 + " " + str2) # 输出: Hello World
# 重复操作符 *
print(str1 * 3) # 输出: HelloHelloHello
# 成员操作符 in
print("He" in str1) # 输出: True
5. 字符串的转义字符
# 常用转义字符
print("First line\nSecond line") # 换行
print("Tab\tspacing") # 制表符
print("Backslash\\") # 反斜杠
print("Single quote\'") # 单引号
print("Double quote\"") # 双引号
6. 字符串的不可变性
Python 中的字符串是不可变的,这意味着一旦创建就不能修改。如果需要修改字符串,需要创建一个新的字符串。
text = "Hello"
# text[0] = "h" # 这会引发错误
# 正确的方式是创建新的字符串
text = "h" + text[1:] # 输出: hello
7. 字符串的编码
# 字符串编码
text = "你好"
encoded = text.encode('utf-8')
print(encoded) # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'
# 字符串解码
decoded = encoded.decode('utf-8')
print(decoded) # 输出: 你好
