Python学习,第四课 - 字符串相关操作

这次主要说说Python中字符串的使用方法详解

capitalize  首字母大写
print('chengshou'.capitalize())
#输出结果:Chengshou

title  修改成标题模式 - 既单词的首字母大写
print('cheng shou'.title())
#输出结果:Cheng Shou
count  查询字符在字符串中的个数
print('chengshou'.count("h"))
#输出结果:2
center  字符不足数量则补齐
print('chengshou'.center(30, '-'))
#输出结果:----------chengshou-----------
#可以看到在字符的左右两边加上了多个“-”符号,知道字符串满30个字符
endswith  判断字符串是否已制定字符结尾
print('chengshou'.endswith('s'))
#输出结果:False
print('chengshou'.endswith('u'))
#输出结果:True
find  查找字符串的索引位置
print('chengshou'.find('shou'))
#输出结果:5
isalnum  是否只有阿拉伯数字和英文字母
print('ChengShou99'.isalnum())
#输出结果:True
print('@!#ChengShou99'.isalnum())
#输出结果:False

#这里的字母也包括大写
isalpha  是否纯英文字母
print('ChengShou'.isalpha())
#输出结果:True
print('ChengShou99'.isalpha())
#输出结果:False
isdigit  是否整数
print('99'.isdigit())
#输出结果:True
print('99.9'.isdigit())
#输出结果:False
isidentifier  判断是不是一个合法的标识符(就是是否合法的变量名)
print('ChengShou'.isidentifier())
#输出结果:True
print('Cheng Shou'.isidentifier())
#输出结果:False

#关于合法的变量名我们在第一课的变量里有详细说过哪些变量名是不合法的,
#如果用到不合法的这里都会识别到
 
islower  判断是否全小写
print('chengshou'.islower())
#输出结果:True
print('ChengShou'.islower())
#输出结果:False
 
isspace  判断是否全空格
print('    '.isspace())
#输出结果:True

#字符串中只有空格,不管几个空格,返回都是True,否则False
 
isupper  判断是否全大写
print('CHENGSHOU'.isupper()) 
#输出结果:True

#只有字符串中全部的字母都是大写才返回True
 
join  对列表重新拼接成字符串,这个方法后期使用比较频繁
print('+'.join(['a', 'b', 'c', 'd']))
#输出结果:a+b+c+d
 
ljust  字符不足数量则左边补齐
print('chengshou'.ljust(30, '*'))
#输出结果:chengshou*********************

rjust  字符不足数量则右边补齐
print('chengshou'.rjust(30, '-'))
#输出结果:---------------------chengshou

lower  大写转小写
print('CHENGSHOU'.lower())
#输出结果:chengshou
 
upper  小写转大写
print('chengshou'.upper())
#输出结果:CHENGSHOU
 
lstrip  去除左边的空格和回车
print('\nchengshou'.lstrip())
#输出结果:chengshou
 
rstrip  去除右边的空格和回车
print('chengshou\n'.rstrip())
#输出结果:chengshou
 
strip  去除前后的空格和回车
print('\nchengshou\n'.strip())
#输出结果:chengshou
 
replace  替换字符串中的字符,默认替换全部
print('chengshou'.replace('h', 'A', 1))
#输出结果:cAengshou

#第三个参数是控制替换字符的数量,
#传1则替换左边第一个匹配到的字符
#传2则替换左边第一个和第二个匹配到的字符
#默认可以不填,匹配所有的字符
 
rfind  获取最右边的字符索引
print('chengshou'.rfind('h'))
#输出结果:6

#从右边开始匹配字符,返回匹配到的字符索引
 
split  分割字符串,这个也非常常用
print('chengshou'.split('h'))
#输出结果:['c', 'engs', 'ou']

#分割返回的是一个列表
 
swapcase  大写转小写,小写的转大写
print('ChengShou'.swapcase())
#输出结果:cHENGsHOU


以上就是Python中字符串的大部分方法,还有一些极其特殊和少用的没有展示出来。

当然对于普通的Python使用,以上的这些已经足够日常使用了。

如果大家有是补充欢迎评论区留言!谢谢大家!

猜你喜欢

转载自www.cnblogs.com/yidaoge/p/12241840.html