了解Python的字符串函数及其用法
Python是一种高级编程语言,已经成为各个行业广泛使用的语言之一。Python中处理字符串的能力非常强大,标准库提供了大量的字符串处理函数和用法。本文将介绍一些常用的Python字符串函数及其用法。
1. len()
len()函数用来获取字符串的长度,即字符串中字符的数量。
示例:
str1 = 'hello world' print(len(str1)) # 11
2. str.lower()和str.upper()
lower()函数将字符串中的所有字母转换为小写,upper()函数将字符串中的所有字母转换为大写。
示例:
str1 = 'Hello World' print(str1.lower()) # hello world print(str1.upper()) # HELLO WORLD
3. str.count()
count()函数返回指定的字符串在当前字符串中出现的次数。
示例:
str1 = 'hello world'
print(str1.count('o')) # 2
4. str.find()和str.index()
find()函数返回指定的子字符串 次出现的位置,如果没有找到则返回-1,index()函数与之类似,但是如果没有找到子字符串则会引发ValueError异常。
示例:
str1 = 'hello world'
print(str1.find('world')) # 6
print(str1.index('world')) # 6
5. str.replace()
replace()函数将字符串中指定的子字符串替换为新的子字符串。
示例:
str1 = 'hello world'
print(str1.replace('world', 'python')) # hello python
6. str.split()
split()函数以指定的分隔符将字符串分割为多个子字符串,并返回一个包含子字符串的列表。
示例:
str1 = 'hello world'
print(str1.split(' ')) # ['hello', 'world']
7. str.strip()
strip()函数返回一个删除了字符串首尾空格的新字符串。
示例:
str1 = ' hello world ' print(str1.strip()) # hello world
8. str.join()
join()函数以指定的字符串作为分隔符,连接序列中的元素,生成一个新的字符串。
示例:
list1 = ['hello', 'world'] str1 = ' ' print(str1.join(list1)) # hello world
9. str.startswith()和str.endswith()
startswith()函数返回True,如果字符串以指定的字符开头,否则返回False,endswith()函数返回True,如果字符串以指定的字符结尾,否则返回False。
示例:
str1 = 'hello world'
print(str1.startswith('hello')) # True
print(str1.endswith('world')) # True
10. str.isalpha()和str.isdigit()
isalpha()函数返回True,如果字符串只包含字母,否则返回False,isdigit()函数返回True,如果字符串只包含数字,否则返回False。
示例:
str1 = 'hello' str2 = '123' print(str1.isalpha()) # True print(str2.isdigit()) # True
以上是Python中一些常用字符串函数及其用法,这些函数都可以很好的帮助我们处理字符串,让我们的代码更加简洁易懂,提高我们的工作效率。
