Python中的字符串函数:常用的内置函数及示例
Python中的字符串是不可变的序列,字符串对象有很多内置函数可以直接使用。本文将介绍一些常用的字符串函数以及示例,帮助你更好地理解和使用字符串操作。
1. len():返回字符串的长度。
str1 = "Hello World" print(len(str1)) # 输出 11
2. lower():将字符串中的大写字母转换为小写。
str2 = "Hello World" print(str2.lower()) # 输出 "hello world"
3. upper():将字符串中的小写字母转换为大写。
str3 = "Hello World" print(str3.upper()) # 输出 "HELLO WORLD"
4. capitalize():将字符串的首字母转换为大写,其他字符转换为小写。
str4 = "hello world" print(str4.capitalize()) # 输出 "Hello world"
5. title():将每个单词的首字母转换为大写。
str5 = "hello world" print(str5.title()) # 输出 "Hello World"
6. islower():检查字符串是否全是小写字母。
str6 = "hello world" print(str6.islower()) # 输出 True
7. isupper():检查字符串是否全是大写字母。
str7 = "HELLO WORLD" print(str7.isupper()) # 输出 True
8. isdigit():检查字符串是否全是数字字符。
str8 = "12345" print(str8.isdigit()) # 输出 True
9. isalpha():检查字符串是否全是字母字符。
str9 = "hello" print(str9.isalpha()) # 输出 True
10. isalnum():检查字符串是否全是字母或数字字符。
str10 = "hello123" print(str10.isalnum()) # 输出 True
11. isspace():检查字符串是否全是空白字符(空格、制表符、换行符等)。
str11 = " " print(str11.isspace()) # 输出 True
12. strip():删除字符串开头和结尾的空白字符。
str12 = " hello world " print(str12.strip()) # 输出 "hello world"
13. startswith():检查字符串是否以指定的前缀开始。
str13 = "Hello World"
print(str13.startswith("Hello")) # 输出 True
14. endswith():检查字符串是否以指定的后缀结尾。
str14 = "Hello World"
print(str14.endswith("World")) # 输出 True
15. replace():将字符串中的指定子串替换为另一个字符串。
str15 = "Hello World"
print(str15.replace("World", "Python")) # 输出 "Hello Python"
16. split():将字符串按照指定的分隔符分割成列表。
str16 = "Hello,World"
print(str16.split(",")) # 输出 ["Hello", "World"]
17. join():将一个列表中的字符串使用指定的分隔符连接起来。
list17 = ["Hello", "World"]
print(",".join(list17)) # 输出 "Hello,World"
18. find():查找字符串中是否包含指定的子串,并返回其第一次出现的索引,如果找不到则返回 -1。
str18 = "Hello World"
print(str18.find("World")) # 输出 6
19. count():统计字符串中指定子串出现的次数。
str19 = "Hello World"
print(str19.count("l")) # 输出 3
20. format():根据指定的格式将值插入到字符串中。
str20 = "Hello {0}"
print(str20.format("World")) # 输出 "Hello World"
以上就是一些常用的字符串函数及其示例。通过使用这些内置函数,可以方便地对字符串进行各种操作和处理,提高编程效率。
