info = 'xie|12|man'print(info.split('|')) # ['xie','12','man']#split的第二个参数maxsplit设置分割的次数,默认左往右计数。
info = 'xie|12|man'print(info.split('|',maxsplit=1)) # ['xie', '12|man']#可以使用lsplit、rsplit设置分割的方向。
info = 'xie|12|man'print(info.lsplit('|',maxsplit=1)) # ['xie', '12|man']print(info.rsplit('|',maxsplit=1)) # ['xie|12','man']
改变字符串字母的大小写。
name = 'xie'print(name.upper()) # 'XIE'
name2 = 'XIE'print(name.lower()) # 'xie'
判断字符串是否以指定的字符开头或结尾。
word = 'Long may the sunshine'print(word.startswith('m')) # Falseprint(word.startswith('L')) # Trueprint(word.endswith('sunshine')) # Trueprint(word.endswith('n')) # False
格式化输出
#1.格式化输出第一种方式,按照传参的顺序
info = 'My name is {},i am {} years old.'print(info.format('xie',18)) # My name is xie,i am 18 years old.#2.格式化输出第二种方式,可以多次使用
info = 'My name is {1},i am {0} years old.{0}'print(info.format(18,'xie')) # My name is xie,i am 18 years old.18#3.格式化输出第三种方式,参数名方式
info = 'My name is {name},i am {age} years old.'print(info.format(name = 'xie', age = 18)) # My name is xie,i am 18 years old.
word = 'Long may the sunshine.'# replace()方法中第一个参数是被替换的字符,第二个是新的字符,第三个是替换的数量。print(word.replace(' ','|')) # 'Long|may|the|sunshine.' 默认全替换print(word.replace(' ','|',1)) # 'Long|may the sunshine.'
判断字符串是否是纯数字
num = '7'print(num.isdigit()) # True
查找字符在字符串中的位置及出现次数
word = 'Long may the sunshine.'# find(sub,start,end) sub:查找的字符、start:开始位置、end:结束位置 。print(word.find('t')) # 9print(word.find('s',5,20)) # 13 's'第一次出现的索引print(word.find('r')) # -1 没找到返回-1# index()方法同find类似,但是没找到不返回-1而是报错print(word.count('s')) # 2 count()方法返回次数
其他方法
# title 每个单词首字母大写print('what are you doing'.title()) # What Are You Doing# capitalize 字符串头大写print('what are you doing'.capialize()) # What are you doing# center 字符居中,长度不够的*号补全print('xie'.center('*',7)) # '**xie**'# rjust 字符右对齐,长度不够*号补全print('xie'.rjust('*',4)) # '*xie'# ljust 字符左对齐,长度不够*号补全print('xie'.ljust('*',4)) # 'xie*'# isalnum()判断既可以包含字母也可以包含数字# isalpha()判断是否全是字母
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署