欢迎访问宙启技术站
智能推送

了解Python常用的字符串函数

发布时间:2023-06-20 01:48:43

在Python中,字符串是一种常用的数据类型。字符串函数是对字符串进行操作和处理的方法,Python中有很多内置的字符串函数,如下所示:

1. len():返回字符串的长度。

2. str.lower():将字符串转换为小写字母。

3. str.upper():将字符串转换为大写字母。

4. str.isdigit():判断字符串是否只包含数字。

5. str.isalpha():判断字符串是否只包含字母。

6. str.isalnum():判断字符串是否只包含数字和字母。

7. str.strip():去除字符串首尾的空格。

8. str.replace():替换字符串中的子串。

9. str.split():以指定的分隔符分割字符串。

10. str.join():将字符串列表合并成一个字符串。

11. str.startswith():判断字符串是否以指定的子串开头。

12. str.endswith():判断字符串是否以指定的子串结尾。

13. str.find():查找字符串中是否包含指定的子串,返回子串的位置,如果不包含则返回-1。

14. str.count():统计字符串中指定子串出现的次数。

下面给出一些常见字符串函数的用法和实例:

1. len()

len(str)函数用于返回字符串的长度,即字符串中字符的个数。

str = "Hello, world!"
print(len(str))   # 输出 13

2. str.lower()

str.lower()函数用于将字符串中所有的大写字母转换成小写字母。

str = "Hello, WORLD!"
print(str.lower())   # 输出 hello, world!

3. str.upper()

str.upper()函数用于将字符串中所有的小写字母转换成大写字母。

str = "Hello, world!"
print(str.upper())   # 输出 HELLO, WORLD!

4. str.isdigit()

str.isdigit()函数用于判断字符串是否只包含数字。

str1 = "123456"
str2 = "123abc"
print(str1.isdigit())   # 输出 True
print(str2.isdigit())   # 输出 False

5. str.isalpha()

str.isalpha()函数用于判断字符串是否只包含字母。

str1 = "abcdef"
str2 = "123abc"
print(str1.isalpha())   # 输出 True
print(str2.isalpha())   # 输出 False

6. str.isalnum()

str.isalnum()函数用于判断字符串是否只包含数字和字母。

str1 = "123456"
str2 = "abc123"
str3 = "abc,123"
print(str1.isalnum())   # 输出 True
print(str2.isalnum())   # 输出 True
print(str3.isalnum())   # 输出 False

7. str.strip()

str.strip()函数用于去除字符串头尾的空格。

str = "   Hello, world!   "
print(str.strip())   # 输出 Hello, world!

8. str.replace()

str.replace()函数用于将字符串中的指定子串替换成新的子串。

str = "Hello, world!"
new_str = str.replace("world", "Python")
print(new_str)   # 输出 Hello, Python!

9. str.split()

str.split()函数用于以指定的分隔符将字符串分割成一个列表。

str = "Hello, world!"
list1 = str.split(",")   # 以逗号分割字符串
list2 = str.split(" ")   # 以空格分割字符串
print(list1)   # 输出 ['Hello', ' world!']
print(list2)   # 输出 ['Hello,', 'world!']

10. str.join()

str.join()函数用于将一个字符串列表合并成一个字符串。

list1 = ["Hello", "world", "!"]
str1 = " ".join(list1)   # 将列表合并成字符串,用空格分隔
print(str1)   # 输出 Hello world !

11. str.startswith()

str.startswith()函数用于判断字符串是否以指定的子串开头。

str = "Hello, world!"
print(str.startswith("Hello"))   # 输出 True
print(str.startswith("world"))   # 输出 False

12. str.endswith()

str.endswith()函数用于判断字符串是否以指定的子串结尾。

str = "Hello, world!"
print(str.endswith("!"))   # 输出 True
print(str.endswith("world"))   # 输出 False

13. str.find()

str.find()函数用于查找字符串中是否包含指定的子串,如果包含则返回子串的位置,如果不包含则返回-1。

str = "Hello, world!"
index1 = str.find("world")   # 查找子串 "world" 的位置
index2 = str.find("Python")   # 查找子串 "Python" 的位置
print(index1)   # 输出 7
print(index2)   # 输出 -1

14. str.count()

str.count()函数用于统计字符串中指定子串出现的次数。

str = "Hello, world!"
count1 = str.count("o")   # 统计字母 "o" 出现的次数
count2 = str.count("l")   # 统计字母 "l" 出现的次数
print(count1)   # 输出 2
print(count2)   # 输出 3

综上所述,Python中的字符串函数为我们处理和操作字符串提供了很多便利。对于从事Python开发的人员来说,熟悉常用的字符串函数是非常必要的。