python中str的使用
在 Python 中,str
(字符串)是不可变的数据类型,用于存储文本数据。Python 提供了丰富的字符串操作方法,下面是对 str
类型的详细讲解。
1. 创建字符串
Python 中可以使用单引号 '
、双引号 "
或 三引号 ''' """
创建字符串:
s1 = 'hello'
s2 = "hello"
s3 = '''hello'''
s4 = """hello"""
print(s1, s2, s3, s4) # 输出:hello hello hello hello
三引号 主要用于多行字符串:
s = """这是一个
多行字符串"""
print(s)
2. 字符串的基本操作
2.1 拼接 +
和重复 *
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Hello World
print(s1 * 3) # HelloHelloHello
2.2 获取字符串长度 len()
s = "Python"
print(len(s)) # 6
2.3 访问字符串中的字符(索引 & 切片)
Python 中字符串支持 索引 (indexing)和 切片 (slicing):
s = "Python"
print(s[0]) # P(索引从 0 开始)
print(s[-1]) # n(倒数第 1 个字符)
切片(截取子串)
print(s[1:4]) # "yth"(索引 1 到 3)
print(s[:4]) # "Pyth"(从头到索引 3)
print(s[2:]) # "thon"(索引 2 到末尾)
print(s[::-1]) # "nohtyP"(反转字符串)
3. 字符串常用方法
Python 提供了丰富的字符串操作方法:
3.1 大小写转换
s = "Python Programming"
print(s.lower()) # python programming
print(s.upper()) # PYTHON PROGRAMMING
print(s.capitalize()) # Python programming
print(s.title()) # Python Programming
3.2 去除空格 strip()
s = " hello "
print(s.strip()) # "hello"(去掉前后空格)
print(s.lstrip()) # "hello "(去掉左侧空格)
print(s.rstrip()) # " hello"(去掉右侧空格)
3.3 查找和替换
s = "hello world"
print(s.find("world")) # 6(找到"world"的索引)
print(s.replace("world", "Python")) # "hello Python"
3.4 字符串分割和连接
s = "apple,banana,orange"
words = s.split(",") # 按逗号分割成列表
print(words) # ['apple', 'banana', 'orange']
new_s = "-".join(words) # 用 "-" 连接列表元素
print(new_s) # "apple-banana-orange"
4. 格式化字符串
Python 支持多种字符串格式化方法。
4.1 f-string(推荐)
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
4.2 format() 方法
print("My name is {} and I am {} years old.".format(name, age))
4.3 旧式 %
格式化
print("My name is %s and I am %d years old." % (name, age))
5. 字符串的判断方法
s = "hello123"
print(s.isalpha()) # False(包含数字,不是纯字母)
print(s.isdigit()) # False(包含字母,不是纯数字)
print(s.isalnum()) # True(字母+数字)
print(" ".isspace()) # True(纯空格)
print("Python".startswith("Py")) # True
print("Python".endswith("on")) # True
6. 字符串的不可变性
Python 的字符串是**不可变(immutable)**的,不能直接修改:
s = "hello"
# s[0] = "H" # ❌ 会报错
s = "Hello" # ✅ 只能重新赋值
7. 字符串的编码
Python 默认使用 UTF-8 编码,可以使用 encode()
和 decode()
进行转换:
s = "你好"
encoded_s = s.encode("utf-8") # 编码为字节
print(encoded_s) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
decoded_s = encoded_s.decode("utf-8") # 解码回字符串
print(decoded_s) # 你好
总结:
- 字符串是不可变的 ,不能修改其中的字符,只能重新赋值。
- 支持索引和切片 ,可以提取子串、倒序排列等。
- 提供丰富的字符串方法 ,如大小写转换、查找、替换、分割、连接等。
- 支持格式化输出 ,推荐使用
f-string
。