“Python的字符串处理及相关函数的使用”
Python 是目前最流行的编程语言之一,其拥有丰富的库和工具,特别是在字符串处理方面有许多方便且实用的函数,在数据处理、文本分析、爬虫等领域广泛使用。本篇文章将讲解 Python 中字符串处理及相关函数的使用。
字符串定义
在 Python 中,字符串是以单引号(’)或双引号(”)括起来的一串字符,可以包含字母、数字、特殊字符以及空格等,例如:
str1 = 'Hello world!' str2 = "Python is awesome."
字符串处理函数
1. 字符串大小写转换
Python 提供了三个函数用于字符串大小写转换,分别为 lower(), upper() 和 capitalize()
str1 = 'Hello World!' print(str1.lower()) #输出hello world! print(str1.upper()) #输出HELLO WORLD! print(str1.capitalize()) #输出Hello world!
2. 字符串查找和替换
字符串查找使用 find() 或 index() 函数,其中 find() 方法返回字符串中第一个匹配项的索引,如果没有匹配项,则返回 -1。index() 方法与 find() 方法类似,不同之处在于,如果没有匹配项,则会引发一个 ValueError 异常。
str1 = 'Hello World!'
print(str1.find('o')) #输出4
print(str1.index('o')) #输出4
print(str1.find('z')) #输出-1
print(str1.index('z')) #抛出ValueError异常
替换字符串中的某些字符,可以使用 replace() 方法。
str1 = 'Hello World!'
print(str1.replace('l', 'L')) #输出HeLLo WorLd!
3. 字符串拼接和分割
字符串连接使用 + 运算符,字符串分割使用 split() 函数。
str1 = 'Hello'
str2 = 'World'
print(str1 + ' ' + str2) #输出Hello World
str3 = '1,2,3,4,5'
print(str3.split(',')) #输出['1', '2', '3', '4', '5']
4. 字符串格式化
Python 通过 % 运算符或 format() 方法来进行字符串格式化。使用 % 运算符时,可以在字符串中插入格式化代码 %s 表示字符串,%d 表示整数,%f 表示浮点数,%.2f 表示保留两位小数,%% 表示一个百分号。
str1 = 'Hello %s'
print(str1 % 'World') #输出Hello World
age = 20
print('My age is %d' % age) #输出My age is 20
price = 3.1415926
print('The price is %.2f' % price) #输出The price is 3.14
print('There are %d%% students in the class' % 80) #输出There are 80% students in the class
message = 'My name is {}, I am {} years old'.format('Tom', 20)
print(message) #输出My name is Tom, I am 20 years old
字符串处理实例
下面我们以一个字符串操作的实例来展示 Python 中字符串处理的应用。假设我们需要从一个文本文件中读取数据,其中每行数据格式为“name age sex”,我们希望计算文件中男女人数,并输出总人数、男女比例等数据。
我们先定义一个函数 count_sex(),该函数接受一个文件名参数 filename,遍历文件中的每行数据,统计出男女人数和总人数,并返回这些数据。
def count_sex(filename):
male_count = 0
female_count = 0
total_count = 0
with open(filename, 'r') as f:
lines = f.readlines()
for line in lines:
total_count += 1
data = line.strip().split(' ')
sex = data[2]
if sex == 'M':
male_count += 1
elif sex == 'F':
female_count += 1
return male_count, female_count, total_count
我们调用该函数,并计算男女比例:
male, female, total = count_sex('data.txt')
print('Total: %d' % total)
print('Male: %d, Female: %d' % (male, female))
print('Male Female Ratio: %.2f%% : %.2f%%' % (male / total * 100, female / total * 100))
运行结果如下:
Total: 7 Male: 3, Female: 4 Male Female Ratio: 42.86% : 57.14%
以上就是 Python 中常用的字符串处理及相关函数的用法,这些函数可以大大简化我们在字符串处理方面的编程工作,提高我们的工作效率。
