在 Python3 中,字符串(str
)是不可变的序列,支持多种方法用于处理文本数据。以下是字符串的常用方法及其使用示例:
1. str.lower()
和 str.upper()
- 作用:将字符串转换为小写或大写。
- 示例:
text = "Hello World" print(text.lower()) # 输出: hello world print(text.upper()) # 输出: HELLO WORLD
2. str.strip([chars])
- 作用:移除字符串首尾的指定字符(默认移除空格、换行符等空白字符)。
- 示例:
text = " \t Hello World! \n" print(text.strip()) # 输出: "Hello World!" text = "www.example.com" print(text.strip("w.moc")) # 输出: "example"
3. str.replace(old, new[, count])
- 作用:替换字符串中的指定子串,可指定替换次数。
- 示例:
text = "Hello World" print(text.replace("World", "Python")) # 输出: "Hello Python" text = "apple, apple, banana" print(text.replace("apple", "cherry", 1)) # 输出: "cherry, apple, banana"
4. str.split(sep=None, maxsplit=-1)
- 作用:按指定分隔符将字符串分割为列表(默认按空格分割)。
- 示例:
text = "Hello, World! Python" print(text.split()) # 输出: ['Hello,', 'World!', 'Python'] print(text.split(",")) # 输出: ['Hello', ' World! Python'] print(text.split(" ", 1)) # 输出: ['Hello,', 'World! Python']
5. str.join(iterable)
- 作用:将可迭代对象(如列表、元组)的元素用指定字符串连接成新字符串。
- 示例:
words = ["Hello", "World", "Python"] print("-".join(words)) # 输出: "Hello-World-Python" numbers = [1, 2, 3] print(", ".join(str(n) for n in numbers)) # 输出: "1, 2, 3"
6. str.startswith(prefix[, start[, end]])
和 str.endswith(suffix[, start[, end]])
- 作用:检查字符串是否以指定前缀或后缀开头/结尾,可指定检查范围。
- 示例:
text = "Hello World" print(text.startswith("Hello")) # 输出: True print(text.endswith("World")) # 输出: True
7. str.find(sub[, start[, end]])
和 str.index(sub[, start[, end]])
- 作用:查找子串在字符串中第一次出现的索引,不存在时
find()
返回-1
,index()
报错。 - 示例:
text = "Hello World" print(text.find("World")) # 输出: 6 print(text.find("Python")) # 输出: -1 # print(text.index("Python")) # 报错: ValueError
8. str.count(sub[, start[, end]])
- 作用:统计子串在字符串中出现的次数。
- 示例:
text = "apple, banana, apple" print(text.count("apple")) # 输出: 2
9. str.isalpha()
, str.isdigit()
, str.isalnum()
- 作用:检查字符串是否全为字母、数字或字母数字组合。
- 示例:
print("abc".isalpha()) # 输出: True print("123".isdigit()) # 输出: True print("abc123".isalnum()) # 输出: True print("abc!".isalnum()) # 输出: False
10. str.format(*args, **kwargs)
- 作用:格式化字符串(Python 3.6+ 推荐使用 f-strings)。
- 示例:
name = "Alice" age = 30 print("Hello, {}! You are {}.".format(name, age)) # 输出: "Hello, Alice! You are 30." # 位置参数 print("{0} and {1}".format("apple", "banana")) # 输出: "apple and banana" # 关键字参数 print("{name} is {age} years old.".format(name="Bob", age=25)) # 输出: "Bob is 25 years old."
11. str.center(width[, fillchar])
- 作用:将字符串居中,并使用指定字符填充至指定宽度。
- 示例:
text = "Hello" print(text.center(11, "-")) # 输出: "---Hello---"
12. str.zfill(width)
- 作用:在字符串左侧填充零至指定宽度(常用于数字补零)。
- 示例:
num = "42" print(num.zfill(5)) # 输出: "00042"
13. str.encode(encoding="utf-8", errors="strict")
- 作用:将字符串编码为字节(bytes)对象。
- 示例:
text = "你好" encoded = text.encode("utf-8") print(encoded) # 输出: b'\xe4\xbd\xa0\xe5\xa5\xbd'
14. str.format_map(mapping)
- 作用:使用字典映射格式化字符串。
- 示例:
person = {"name": "Alice", "age": 30} print("Hello, {name}! You are {age}.".format_map(person)) # 输出: "Hello, Alice! You are 30."
15. str.maketrans(table)
和 str.translate(table)
- 作用:创建字符映射表并替换字符(常用于批量替换)。
- 示例:
# 创建映射表:将 'a' 替换为 'A','b' 替换为 'B' table = str.maketrans("ab", "AB") text = "apple banana" print(text.translate(table)) # 输出: "Apple BAnAnA"
总结
字符串方法常用于文本处理,常见操作包括:
- 大小写转换:
lower()
、upper()
- 去空格/字符:
strip()
- 替换/分割/连接:
replace()
、split()
、join()
- 查找/统计:
find()
、index()
、count()
- 判断类型:
isalpha()
、isdigit()
、isalnum()
- 格式化:
format()
、f-strings
建议结合实际需求选择合适的方法,例如:
- 清理文本用
strip()
、replace()
。 - 解析数据用
split()
、join()
。 - 格式化输出用 f-strings(更简洁):
f"Hello, {name}!"
。 - 编码转换用
encode()
、decode()
。