10个有用的Python字符串函数小结

请问下,10个有用的Python字符串函数小结
最新回答
思慕

2026-10-21 22:16:56

以下是10个常用的Python字符串函数及其核心功能总结:

1. capitalize()
  • 功能:将字符串的第一个字符转换为大写,其余字符转换为小写。
  • 语法:string.capitalize()
  • 示例:string = "hello world"print(string.capitalize()) # 输出:Hello world
  • 注意:若首字符为数字或符号,仅后续字母受影响。
2. lower()
  • 功能:将字符串中所有字母转换为小写,忽略数字和符号。
  • 语法:string.lower()
  • 示例:string = "Hello 123"print(string.lower()) # 输出:hello 123
3. title()
  • 功能:将字符串中每个单词的首字母大写(类似标题格式)。
  • 语法:string.title()
  • 示例:string = "the quick brown fox"print(string.title()) # 输出:The Quick Brown Fox
  • 注意:单词中的数字或符号后的字母会被大写。
4. casefold()
  • 功能:将所有字符转换为小写,比lower()更彻底(适用于不区分大小写的比较)。
  • 语法:string.casefold()
  • 示例:string = "Stra?e" # 德语单词print(string.casefold()) # 输出:strasse
5. upper()
  • 功能:将字符串中所有字母转换为大写,忽略数字和符号。
  • 语法:string.upper()
  • 示例:string = "Hello 123"print(string.upper()) # 输出:HELLO 123
6. count()
  • 功能:统计子字符串在字符串中出现的次数(可指定范围)。
  • 语法:string.count(value, start, end)
  • 示例:string = "apple banana apple"print(string.count("apple")) # 输出:2
7. find()
  • 功能:返回子字符串首次出现的索引,未找到则返回-1(与index()不同,后者会抛出异常)。
  • 语法:string.find(value, start, end)
  • 示例:string = "hello world"print(string.find("world")) # 输出:6
8. replace()
  • 功能:替换字符串中的子字符串(默认替换所有,可指定替换次数)。
  • 语法:string.replace(oldvalue, newvalue, count)
  • 示例:string = "apple apple apple"print(string.replace("apple", "orange", 2)) # 输出:orange orange apple
9. swapcase()
  • 功能:将字符串中的大小写互换。
  • 语法:string.swapcase()
  • 示例:string = "Hello World"print(string.swapcase()) # 输出:hELLO wORLD
10. join()
  • 功能:将可迭代对象(如列表、元组)中的字符串用指定分隔符连接成一个新字符串。
  • 语法:separator.join(iterable)
  • 示例:words = ["Python", "is", "awesome"]print(" ".join(words)) # 输出:Python is awesome
总结

这些函数覆盖了字符串大小写转换、查找替换、分割连接等常见操作,适用于文本处理、数据清洗等场景。例如:

  • 数据标准化:使用lower()或casefold()统一大小写。
  • 关键词提取:用count()或find()定位子字符串。
  • 格式化输出:通过title()或capitalize()优化显示效果。

掌握这些函数能显著提升Python字符串处理的效率。