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

Python字符串处理常用函数推荐

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

字符串是程序中最常用的数据类型之一,因为它们可以存储和表示文本数据。在 Python 中,有很多内置的字符串处理函数,可以方便地操作和处理字符串。

本文将介绍 Python 字符串处理常用函数,包括字符串的创建、修改、索引、切片、查找和替换等。

1. 创建字符串

在 Python 中创建字符串有多种方法,包括单引号、双引号和三引号。

① 单引号:可以使用单引号来创建一个字符串。

a = 'Hello, World!'

② 双引号:也可以使用双引号来创建一个字符串。

b = "Hello, World!"

③ 三引号:当需要创建多行字符串时,可以使用三引号。

c = """Hello,
World!"""

2. 字符串索引

字符串索引是获取字符串中一个字符的方法。在 Python 中,字符串索引从 0 开始。

str = 'Hello, World!'
print(str[0]) # output: H

3. 字符串切片

字符串切片是从字符串中获取子字符串的方法。在 Python 中,字符串切片使用冒号分隔的两个数字表示起始索引和结束索引。

str = 'Hello, World!'
print(str[0:5]) # output: Hello

4. 字符串长度

字符串长度是指字符串中字符的数量。在 Python 中,字符串长度可以使用内置函数 len() 获取。

str = 'Hello, World!'
print(len(str)) # output: 13

5. 字符串查找

Python 字符串提供了若干函数来查找指定的字符或子字符串。

① find()函数:从字符串的开头开始查找 个匹配的子字符串。如果找到,则返回 个匹配的子字符串的索引值,否则返回 -1。

str = 'Hello, World!'
print(str.find('World')) # output: 7

② rfind()函数:从字符串的末尾开始查找 个匹配的子字符串。如果找到,则返回 个匹配的子字符串的索引值,否则返回 -1。

str = 'Hello, World!'
print(str.rfind('o')) # output: 8

③ index()函数:与 find() 函数类似,但是如果没有找到匹配的子字符串,则会抛出异常。

str = 'Hello, World!'
print(str.index('World')) # output: 7

④ rindex()函数:与 rfind() 函数类似,但是如果没有找到匹配的子字符串,则会抛出异常。

str = 'Hello, World!'
print(str.rindex('o')) # output: 8

6. 字符串替换

Python 字符串提供了若干函数来替换字符串中的指定字符或子字符串。

① replace()函数:将字符串中所有匹配的子字符串替换为指定的字符串。

str = 'Hello, World!'
print(str.replace('Hello', 'Hi')) # output: Hi, World!

② split()函数:将字符串按指定的分隔符分割为一个列表。

str = 'Hello, World!'
print(str.split(',')) # output: ['Hello', ' World!']

③ join()函数:将一个列表中的元素连接为一个字符串。

myList = ['Hello', 'World', '!']
print(' '.join(myList)) # output: Hello World !

7. 字符串转换

Python 字符串提供了若干函数来转换字符串的大小写、字母顺序和空格。

① upper()函数:将字符串转换为大写。

str = 'Hello, World!'
print(str.upper()) # output: HELLO, WORLD!

② lower()函数:将字符串转换为小写。

str = 'Hello, World!'
print(str.lower()) # output: hello, world!

③ title()函数:将字符串中每个单词的首字母大写。

str = 'hello, world!'
print(str.title()) # output: Hello, World!

④ swapcase()函数:将字符串中的大小写字符互换。

str = 'Hello, World!'
print(str.swapcase()) # output: hELLO, wORLD!

8. 字符串判断

Python 字符串提供了若干函数来判断字符串中的字符类型、空格和数字。

① isalpha()函数:判断字符串是否只包含字母字符。

str1 = 'Hello'
str2 = 'Hello, World!'
print(str1.isalpha()) # output: True
print(str2.isalpha()) # output: False

② isdigit()函数:判断字符串是否只包含数字字符。

str1 = '123'
str2 = 'Hello, World!'
print(str1.isdigit()) # output: True
print(str2.isdigit()) # output: False

③ isspace()函数:判断字符串是否只包含空格字符。

str1 = '   '
str2 = 'Hello, World!'
print(str1.isspace()) # output: True
print(str2.isspace()) # output: False

9. 字符串格式化

字符串格式化是将变量或表达式插入到字符串中的方法,使输出更加清晰和易读。

① 使用 % 符号格式化字符串。

name = 'Alice'
score = 95
print('%s scored %d in the exam.' % (name, score)) # output: Alice scored 95 in the exam.

② 使用 {} 格式化字符串,用 .format() 方法传递参数。

name = 'Alice'
score = 95
print('{} scored {} in the exam.'.format(name, score)) # output: Alice scored 95 in the exam.

Python 字符串处理是程序开发中非常重要的一部分,有了这些常用函数,可以更加方便地操作和处理字符串,提高开发效率。