Python中的字符串函数及其使用方法
发布时间:2023-07-27 15:39:34
Python提供了很多字符串函数和方法,用于处理和操作字符串。下面是一些常用的字符串函数及其使用方法:
1. len():返回字符串的长度
string = "Hello World!" print(len(string)) # 输出:12
2. capitalize():将字符串的首字母大写,其他字母小写
string = "hello world" print(string.capitalize()) # 输出:Hello world
3. upper():将字符串中的所有字母转换为大写
string = "hello world" print(string.upper()) # 输出:HELLO WORLD
4. lower():将字符串中的所有字母转换为小写
string = "HELLO WORLD" print(string.lower()) # 输出:hello world
5. title():将字符串中每个单词的首字母大写,其他字母小写
string = "hello world" print(string.title()) # 输出:Hello World
6. count():返回字符串中指定子字符串的出现次数
string = "hello world"
print(string.count("l")) # 输出:3
7. find():查找子字符串在字符串中的位置,如果找不到返回-1
string = "hello world"
print(string.find("world")) # 输出:6
8. replace():将字符串中的指定子字符串替换为新的字符串
string = "hello world"
print(string.replace("world", "python")) # 输出:hello python
9. split():按照指定分隔符将字符串分割成多个子字符串,返回一个列表
string = "hello world"
print(string.split(" ")) # 输出:['hello', 'world']
10. join():将一个列表中的所有元素连接成一个字符串,可以指定连接符
list = ['hello', 'world']
print(" ".join(list)) # 输出:hello world
11. isalpha():判断字符串是否只包含字母字符
string = "hello" print(string.isalpha()) # 输出:True
12. isdigit():判断字符串是否只包含数字字符
string = "123" print(string.isdigit()) # 输出:True
以上只是一些常用的字符串函数和方法,Python还提供了更多用于字符串处理的函数和方法。
