Python常用字符串处理函数大全
Python是一种强大的编程语言,可以完成广泛的任务。在数据处理方面,Python具有许多强大的功能和库,包括字符串处理。在本文中,我们将介绍Python中常用的字符串处理函数。
1. len()
len()函数返回字符串的长度。
例:
str1 = "This is a string."
print(len(str1))
输出:
17
2. .capitalize()
.capitalize()函数将字符串的 个字母变为大写。
例:
str1 = "this is a string."
print(str1.capitalize())
输出:
This is a string.
3. .upper()
.upper()函数将字符串中所有字母变为大写。
例:
str1 = "this is a string."
print(str1.upper())
输出:
THIS IS A STRING.
4. .lower()
.lower()函数将字符串中所有字母变为小写。
例:
str1 = "THIS IS A STRING."
print(str1.lower())
输出:
this is a string.
5. .swapcase()
.swapcase()函数将字符串中所有小写字母变为大写,所有大写字母变为小写。
例:
str1 = "This Is A String."
print(str1.swapcase())
输出:
tHIS iS a sTRING.
6. .title()
.title()函数将字符串中每个单词的首字母变为大写。
例:
str1 = "this is a string."
print(str1.title())
输出:
This Is A String.
7. .startswith()
.startswith()函数检查字符串是否以给定的子字符串开头,并返回True或False。
例:
str1 = "This is a string."
print(str1.startswith('This'))
输出:
True
8. .endswith()
.endswith()函数检查字符串是否以给定的子字符串结尾,并返回True或False。
例:
str1 = "This is a string."
print(str1.endswith('.'))
输出:
True
9. .count()
.count()函数返回给定子字符串在字符串中出现的次数。
例:
str1 = "This is a string."
print(str1.count('is'))
输出:
2
10. .find()
.find()函数返回给定子字符串在字符串中 次出现的位置。
例:
str1 = "This is a string."
print(str1.find('is'))
输出:
2
11. .rfind()
.rfind()函数返回给定子字符串在字符串中最后一次出现的位置。
例:
str1 = "This is a string."
print(str1.rfind('is'))
输出:
5
12. .index()
.index()函数返回给定子字符串在字符串中 次出现的位置,与.find()函数类似。
例:
str1 = "This is a string."
print(str1.index('is'))
输出:
2
13. .rindex()
.rindex()函数返回给定子字符串在字符串中最后一次出现的位置,与.rfind()函数类似。
例:
str1 = "This is a string."
print(str1.rindex('is'))
输出:
5
14. .replace()
.replace()函数将指定子字符串替换为另一个字符串。
例:
str1 = "This is a string."
print(str1.replace('is', 'at'))
输出:
That at a string.
15. .split()
.split()函数将字符串分割为子字符串列表,可以指定分隔符。
例:
str1 = "This is a string."
print(str1.split())
输出:
['This', 'is', 'a', 'string.']
16. .join()
.join()函数将列表中的字符串连接成一个字符串,可以指定连接符。
例:
list1 = ['This', 'is', 'a', 'string.']
print(' '.join(list1))
输出:
This is a string.
17. .strip()
.strip()函数返回删除字符串开头和结尾的所有空格字符后的新字符串。
例:
str1 = " This is a string.
"
print(str1.strip())
输出:
This is a string.
18. .lstrip()
.lstrip()函数返回删除字符串开头的所有空格字符后的新字符串。
例:
str1 = " This is a string.
"
print(str1.lstrip())
输出:
This is a string.
19. .rstrip()
.rstrip()函数返回删除字符串结尾的所有空格字符后的新字符串。
例:
str1 = " This is a string.
"
print(str1.rstrip())
输出:
This is a string.
20. .isalnum()
.isalnum()函数检查字符串是否只包含字母和数字,并返回True或False。
例:
str1 = "Thisis12astring"
print(str1.isalnum())
输出:
True
21. .isalpha()
.isalpha()函数检查字符串是否只包含字母,并返回True或False。
例:
str1 = "Thisisstring"
print(str1.isalpha())
输出:
True
22. .isdigit()
.isdigit()函数检查字符串是否只包含数字,并返回True或False。
例:
str1 = "12345"
print(str1.isdigit())
输出:
True
23. .isspace()
.isspace()函数检查字符串是否只包含空格字符,并返回True或False。
例:
str1 = " "
print(str1.isspace())
输出:
True
以上就是Python常用的字符串处理函数大全。Python很容易学习,所以即使初学者也能轻松使用这些函数有效地处理字符串。
