1.4.1查找
# 1 find 字符串序列.find(字串,開始,結(jié)束) 開始和結(jié)束可以省略mystr ='hello world and itcast and itheima and Python'print(mystr.find('and'))# 12print(mystr.find('and',15,30))# 23print(mystr.find('ands'))# -1# index()print(mystr.index('and'))# 12print(mystr.index('and',15,30))# 23# print(mystr.index('ands')) # 報(bào)錯(cuò)# 3.count()print(mystr.count('and'))# 1print(mystr.count('and',15,30))# 3print(mystr.count('ands'))# 0# 4 rfindprint(mystr.rfind('and'))# 35# 5 rindexprint(mystr.rindex('and'))# 351.4.2修改
# 1 replace(舊子串,新子串,替換次數(shù)) 注:替換次數(shù)如果查出子串出現(xiàn)次數(shù),則替換次數(shù)為該字串出現(xiàn)次數(shù)
mystr ='hello world and itcast and itheima and Python'print(mystr.replace('and','he'))# hello world he itcast he itheima he Pythonprint(mystr.replace('and','he',2))# hello world he itcast he itheima and Pythonprint(mystr)# hello world and itcast and itheima and Python'''
數(shù)據(jù)按照是否直接修改分為可變類型和不可變類型。
字符串類型的數(shù)據(jù)修改的時(shí)候不能改變?cè)凶址?#xff0c;屬于不可變類型
'''# 2 split(分割字符,num) 注:num表示的是分割的次數(shù),將來返回?cái)?shù)據(jù)個(gè)數(shù)為num+1個(gè)
mystr ='hello world and itcast and itheima and Python'print(mystr.split('and'))# ['hello world ', ' itcast ', ' itheima ', ' Python']print(mystr.split('and',2))# ['hello world ', ' itcast ', ' itheima and Python']print(mystr.split(' '))# ['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']print(mystr.split(' ',2))# ['hello', 'world', 'and itcast and itheima and Python']# 3 join(多字符串組成的序列) 用一個(gè)字符或子串合并字符串,將多個(gè)字符串合并為一個(gè)新的字符串
mylist =['aa','bb','cc']
new_str ='...'.join(mylist)print(new_str)# aa...bb...cc# 1 capitalize() 首字符大寫
mystr ='hello world and itcast and itheima and Python'print(mystr.capitalize())# Hello world and itcast and itheima and python# 2 title() 將每個(gè)單詞的首字母大寫print(mystr.title())# Hello World And Itcast And Itheima And Pythonprint(mystr)# hello world and itcast and itheima and Python# 3 lower() 大寫->小寫# 4 upper() 小寫->大寫# 5 lstrip()刪除字符串左側(cè)的空白字符 rstrip()刪除字符串右側(cè)的空白字符 strip()刪除字符串兩側(cè)的空白字符
str1 =' I 'print(str1.lstrip())# I //print(str1.rstrip())# Iprint(str1.strip())# I# 6 ljust(長(zhǎng)度,填充字符) 返回一個(gè)原字符串左對(duì)齊,并使用指定字符(默認(rèn)空格)填充值對(duì)應(yīng)長(zhǎng)度的新字符串# 同理 rjust,右對(duì)齊 center 居中
str2 ='hello'print(str2.ljust(10,'.'))# hello.....1.4.3判斷
# 1 startswith(子串,開始,結(jié)束)檢查字符串 是否已制定子串開始
mystr ='hello world and itcast and itheima and Python'print(mystr.startswith('hello'))# Trueprint(mystr.startswith('a'))# Falseprint(mystr.startswith('world',6))# True# 2 isalpha() 如果字符串至少有一個(gè)字符并且所有字符都是字母則返回True# 3 isdigit() 只包含數(shù)字 True# 4 isalnum() 如果字符串至少有一個(gè)字符并且所有字符都是數(shù)字或字母則返回True# 5 isspace() 只含有空白True
mystr1 ='hello'print(mystr.isalpha())# Falseprint(mystr1.isalpha())# True