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

Python中的常见字符串操作函数

发布时间:2023-06-10 03:22:24

在Python中,字符串是一种非常常见的数据类型。在处理字符串时,Python提供了许多内置的函数和方法,使得字符串操作变得非常方便和高效。本文将介绍Python中的常见字符串操作函数。

1. len()

len()函数用于返回字符串的长度。

示例代码:

str = "Hello, world!"
print(len(str))

输出结果:

13

2. split()

split()函数用于将字符串按指定分隔符分割为多个子字符串,返回一个字符串列表。

示例代码:

str = "Hello, world!"
print(str.split(",")) # 以逗号为分隔符分割字符串

输出结果:

['Hello', ' world!']

3. join()

join()函数用于将一个序列中的字符串连接为一个新的字符串。

示例代码:

lst = ['Hello', 'world', '!']
print(','.join(lst)) # 以逗号为连接符连接字符串列表中的字符串

输出结果:

Hello,world,!

4. strip()

strip()函数用于去除字符串首尾的指定字符或空格,默认去除空格。

示例代码:

str = "   hello, world   "
print(str.strip()) # 去除字符串首尾空格
print(str.strip('l ')) # 去除字符串首尾空格、小写字母l和空格字符

输出结果:

hello, world
heo, wor

5. replace()

replace()函数用于将字符串中所有旧子字符串替换为新子字符串。

示例代码:

str = "ababababab"
print(str.replace('a', 'c')) # 替换所有a为c
print(str.replace('ab', 'c', 3)) # 替换前3个ab为c

输出结果:

cbcbcbcbcb
ccbcababab

6. lower()

lower()函数用于将字符串中所有字符转换为小写字母。

示例代码:

str = "Hello, World!"
print(str.lower())

输出结果:

hello, world!

7. upper()

upper()函数用于将字符串中所有字符转换为大写字母。

示例代码:

str = "Hello, World!"
print(str.upper())

输出结果:

HELLO, WORLD!

8. startswith()

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

示例代码:

str = "Hello, World!"
print(str.startswith('Hello'))
print(str.startswith('world'))

输出结果:

True
False

9. endswith()

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

示例代码:

str = "Hello, World!"
print(str.endswith('World!'))
print(str.endswith('world!'))

输出结果:

True
False

10. find()

find()函数用于查找指定子字符串在字符串中第一次出现的位置,如果没有找到则返回-1。

示例代码:

str = "Hello, World!"
print(str.find('World'))
print(str.find('world'))

输出结果:

7
-1

11. index()

index()函数用于查找指定子字符串在字符串中第一次出现的位置,如果没有找到则会抛出ValueError。

示例代码:

str = "Hello, World!"
print(str.index('World'))
# print(str.index('world')) # 抛出ValueError异常

输出结果:

7

12. count()

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

示例代码:

str = "Hello, World!"
print(str.count('l'))

输出结果:

3

13. isalpha()

isalpha()函数用于检测字符串是否只由字母组成。

示例代码:

str1 = "Hello, World!"
str2 = "HelloWorld"
print(str1.isalpha())
print(str2.isalpha())

输出结果:

False
True

14. isnumeric()

isnumeric()函数用于检测字符串是否只由数字组成。

示例代码:

str1 = "12345"
str2 = "12345a"
print(str1.isnumeric())
print(str2.isnumeric())

输出结果:

True
False

15. isalnum()

isalnum()函数用于检测字符串是否由字母和数字组成。

示例代码:

str1 = "12345"
str2 = "12345a"
str3 = "HelloWorld"
print(str1.isalnum())
print(str2.isalnum())
print(str3.isalnum())

输出结果:

True
False
True

以上就是Python中常见的字符串操作函数,通过这些函数我们可以轻松地操作和处理字符串,并将其应用到实际开发中。