python 常用的字符串处理函数
find()
功能:检测字符串是否包含特定字符,如果包含,则返回开始的索引;否则返回-1

## find()函数 str = 'hello world' # 'wo'在字符串中 print( str.find('wo') ) # 'wc'不在字符串中 print( str.find('wc') ) ## 输出: ## 6 ## -1
index()
功能:检测字符串是否包含指定字符串,如果包含,则返回开始的索引值,否则提示错误

## index()函数 str = 'hello world' # 'wo'在字符串中 print( str.index('wo') ) # 'wc'不在字符串中,程序报错ValueError,终止运行 print( str.index('wc') ) ## 输出: ## 6 ## ValueError: substring not found
count()
功能:返回str1在string中指定索引范围内批[start,end]出现的次数

## count()函数 str = 'hello world' # 统计str中全部字母l的个数 print( str.count('l') ) # 统计str中从第5+1个字母到最后一个字母中,字母l的个数 print( str.count('l', 5, len(str)) ) ## 输出: ## 3 ## 1
replace()
语法:str1.replace(str2,count)
功能:将str1中的str1替换成str2,如果指定count,则不超过count次

## replace()函数 print('=*'*10, 'replace()函数', '=*'*10) str = 'hello world hello world' str1 = 'world' str2 = 'waltsmith' # 将所有的str1替换为str2 print( str.replace(str1, str2) ) # 只将前1个str1替换为str2 print( str.replace(str1, str2, 1) ) ## 输出: ## hello waltsmith hello waltsmith ## hello waltsmith hello world
split()
语法:
str.split('分界符',maxSplit) naxSplit默认值为-1,表示根据定界符分割所有能分割的,返回值为列表
功能:
如果maxsplit有指定值,则仅分割maxsplit个子字符串

## split()函数 str3 = 'I am a good boy!' # 以空格分割字符串,分界符默认为空格 print(str3.split(' ', 3)) # 以字母o作为分界符,指定最大分割为2,将返回最大分割+1个元素的列表 print(str3.split('o', 2)) ## 输出: ## ['I', 'am', 'a', 'good boy!'] ## ['I am a g', '', 'd boy!']
capitalize()
语法:str.capitalize()
功能:将字符串的首字母大写,其余字母全部小写

## capitalize()函数 str4 = 'I aM waLt smith' # 字符串的首字母大写,其余字母全部小写 print(str4.capitalize()) ## 输出: ## I am walt smith
title()
语法:str.title()
功能:将字符串中所有单词的首字母大写,其余字母全部小写

## title()函数 # 正常字符串的转换 str5 = "I am walt smith!" print(str5.title()) ## 输出: ## I Am Walt Smith! # 字符中包含标点符号 str6 = "I'm walt-sMith!" print(str6.title()) ## 输出: ## I'M Walt-Smith!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了