Python中字符串处理函数的使用方法
发布时间:2023-06-12 07:53:37
Python中有很多字符串处理函数,下面列举了一些常用的函数及其使用方法:
1. len():返回字符串的长度
str = "Hello world" print(len(str)) # 输出 11
2. upper():将字符串中所有字符转换成大写
str = "hello world" print(str.upper()) # 输出 HELLO WORLD
3. lower():将字符串中所有字符转换成小写
str = "HELLO WORLD" print(str.lower()) # 输出 hello world
4. capitalize():将字符串的第一个字符转换成大写
str = "hello world" print(str.capitalize()) # 输出 Hello world
5. title():将字符串中单词的首字母大写
str = "hello world" print(str.title()) # 输出 Hello World
6. strip():去除字符串前后的空格
str = " hello world " print(str.strip()) # 输出 hello world
7. replace():替换字符串中的某个字符
str = "hello world"
print(str.replace("o", "x")) # 输出 hellx wxrld
8. split():切割字符串为列表
str = "hello world"
print(str.split(" ")) # 输出 ['hello', 'world']
9. join():将列表或元组中的字符串合并成一个字符串
str = ['hello', 'world']
print(" ".join(str)) # 输出 hello world
10. find():查找字符串中的某个子串
str = "hello world"
print(str.find("wo")) # 输出 6
11. index():查找字符串中的某个子串,如果未找到则会引起异常
str = "hello world"
print(str.index("wo")) # 输出 6
12. count():统计字符串中某个子串出现的次数
str = "hello world"
print(str.count("o")) # 输出 2
以上就是介绍的十二种 Python 字符串处理函数及其使用方法,可以根据实际需求灵活运用。
