字符串
字符串(string)是用于保守字符信息的数据模型(容器)
字符表类似元素周期表
判断该数据是否存在于字符串当中
str
字符串——判断
判断字符串里面的数据存在的字母是否都是大写
str.isupper()
判断字符串里面的数据存在的字母是否都是小写
str.islower()
判断是否都是数字或者字母
str.isalnum()
判断是否都是字母
str.isalpha()
判断是否全部都是数字
str.isdigit()
判断首字母是否大写
str.istitle()
判断一个人是否姓王startwith(字符串)endswith
str = '王小二'print(str.startswith('王')print(str.endswith('三')运行结果TrueFalse
endswith():判断字符串是否以某个子串结尾
print(mystr.endswith('Python'))print(mystr.endswith('Python'))
isalpha():字母
print(mystr.isalpha())isalpha():数字mystr = '12345'print(mystr.isalpha())
isalnum():数字或字母或组合
print(mystr.isalnum())
字符串——数据转换
将字母全部转换成小写
str.lower()
将字母全部转换成大写
str.upper()
每个单词首字母大写,其他小写
str.title()
单词首字母大写,其他小写
str.capitalize()
字母全部大写
str.swapcase()
字符串——格式转换
str = '**院长**'去掉两侧的指定字符str.strip('*')去掉左侧str.lstrip("*")去掉右侧str.rstrip('*')ljust(长度,占位符)左边占位在右侧补占位符str.ljust(8, "*")补左str.rjust(8, "*")两边都补,优先右边str.center(8, "*")
字符串——拆分与连接
左侧切割成了组数据的元组str.partition('a')右侧切割成了组数据的元组str.rpartition('a')split(字符, 切割数)以指定字符切割数据为列表# 所有a的单词全部切割删除,并拆分单词str.split('a')切割前两个有a的单词列表被分为n+1个部分str.split('a', 2)
对字符串进行占位连接str = '*'print(str.join('钟南山院士'))运行结果钟*南*山*院*士
字符串——查询与替换
str = 'hello world, hello python'find(字符串, 开始索引, 结束索引) 查询print(str.find('a'))print(str.find('a', 5)右边查询,用法同上str.rfind('a')
index和find用法和功能一样,通过字符去找到他的索引值
find如果没有找到指定字符,会返回-1
index如果没有找到指定字符 ,会报错
replace(原字符, 新字符, 替换数量)不指定数量默认全部替换str.replace('a', 'A')
字符串切片
字符串[开始索引:结束索引:步长]str[6:10]
字符串序列find(子串,开始位置下标,结束位置下标)
mystr = "hello world and itcast and itheima and Python"print(mystr.find('and'))# 12print(mystr.find('and', 15, 30)) # 23print(mystr.find('ands')) # -1index():检测某个子串是否包含在这个字符串中,如果在返回这个子串开始的位置下边,否则则报异常。
修改
replace():替换
字符串序列.replace(旧子串,新子串,替换次数)
mystr
split():按照指定字符分割字符串
字符串序列.split(分割字符,num)
注:num表示的是分割字符出现的次数,即将来返回数据个数为num+1
mystr = "hello world and itcast and itheima and Python"# 结果:['hello world', 'itcast', 'itheima','Python']print(mystr.split('and'))# 结果:['hello world', 'itcast', 'itheima and Python']print(mystr.split('and',2))# 结果:['hello world','and','itcast','and','itheima','and','Python']print(mystr.split(' '))# 结果:['hello','world','and itcast and itheima and Python']print(mystr.split(' ', 2))注:如果分割字符是原有字符串中的子串,分割后则丢失该子串
join():用一个字符或子串合并字符串,即是将多个字符串合并为一个新的字符串
字符或子串.join(多字符串组成的序列)
list1 = ['chuan','zhi','bo','ke']t1 = ('aa','b','cc','ddd')# 结果:chuan_zhi_bo_keprint('_'.join(list1))# 结果:aa...b...cc...ddd
poem_list = ["tn登黄鹤楼","王之涣","白日依山尽tn","黄河入海流","欲穷千里目","更上一层楼",]for poem_str in poem_list:# strip()去除空白字符# center居中显示文本print(poem_str.strip().center(10, " "))运行结果登黄鹤楼 王之涣 白日依山尽 黄河入海流 欲穷千里目 更上一层楼