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

内置函数之字符串处理

发布时间:2023-06-09 10:01:58

内置函数是Python自带的一些函数,可以在Python中直接调用,而无需自己编写。字符串是一种常见的数据类型,因此Python提供了许多内置字符串函数,方便我们在程序中处理字符串。本文将介绍一些常用的字符串处理函数。

1. 字符串长度函数

字符串长度函数是len(),可以用来计算一个字符串的长度。例如:

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

结果为13,因为这个字符串有13个字符。

2. 大小写转换函数

Python中有三个字符串大小写转换函数upper()lower()capitalize()

upper()函数将所有小写字母转换为大写字母,例如:

str = 'hello, world!'
print(str.upper())

结果为HELLO, WORLD!

lower()函数将所有大写字母转换为小写字母,例如:

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

结果为hello, world!

capitalize()函数将字符串的第一个字母大写,其他字母均小写,例如:

str = 'hello, world!'
print(str.capitalize())

结果为Hello, world!

3. 查找子字符串函数

Python中字符串查找子字符串函数有三个,分别是find()index()count()

find()函数可以在字符串中查找子字符串,并返回子字符串的起始位置索引,例如:

str = 'hello, world!'
print(str.find('world'))

结果为7,表示子字符串'world'在原字符串中的起始位置索引为7(从0开始)。

如果在字符串中没有找到子字符串,find()函数会返回-1。

index()函数的功能类似于find()函数,但是如果在字符串中没有找到子字符串,会抛出异常,请看下面的例子:

str = 'hello, world!'
print(str.index('world'))

结果同样为7

str = 'hello, world!'
print(str.index('Python'))

这个例子会抛出一个ValueError的异常,因为在字符串中没有找到子字符串'Python'。

count()函数可以用来计算字符串中包含子字符串的个数,例如:

str = 'hello, world!'
print(str.count('o'))

结果为2,因为字符串中包含两个字母'o'。

4. 截取子字符串函数

Python中可以使用下标来截取字符串中的子字符串,也可以使用切片来截取字符串中的子字符串。

使用下标来截取字符串中的子字符串,可以使用[]操作符。例如:

str = 'hello, world!'
print(str[1:4])

结果为ell,因为字符串中从索引1到索引3的字符是'ell'。

使用切片来截取字符串中的子字符串,可以使用:符号。例如:

str = 'hello, world!'
print(str[7:])

结果为world!,因为字符串中从索引7到末尾的字符是'world!'。

5. 字符串替换函数

Python中字符串替换函数是replace(),可以用来将字符串中的某个子字符串替换为另一个字符串,例如:

str = 'hello, world!'
print(str.replace('world', 'Python'))

结果为hello, Python!,因为字符串中的'world'被替换为'Python'了。

6. 字符串分割函数

Python中字符串分割函数是split(),可以将一个字符串按照指定的分隔符进行分割,并返回一个列表。例如:

str = 'hello,world,Python'
print(str.split(','))

结果为['hello', 'world', 'Python'],因为我们以逗号为分隔符,将字符串分割成了3个部分,每个部分都被放入了一个列表中。

7. 字符串格式化函数

Python中字符串格式化函数是format(),可以将变量的值插入到字符串中的占位符中。例如:

name = 'Tom'
age = 18
print('My name is {}, and I am {} years old.'.format(name, age))

结果为My name is Tom, and I am 18 years old.,因为我们使用{}作为占位符,将变量的值插入到了字符串中。

还可以使用{0}{1}等带有索引的占位符来指定变量的顺序和位置。例如:

name = 'Tom'
age = 18
print('My name is {0}, and I am {1} years old.'.format(name, age))

结果同样为My name is Tom, and I am 18 years old.

以上就是Python中常用的字符串处理函数,当你需要对Python字符串进行一些操作时,不妨尝试使用内置函数来实现。