第五章 列表、元组和字符串[DDT书本学习 小甲鱼]【6】

5.3.1 字符串的各种内置方法 表5-1很多暂时略掉!!!!!!!!!
选择几个常用的演示一下
casefold()方法,它的作用是将字符串的所有字符变为小写
代码
str1="DaoDanTou"
print(str1.casefold())
------------------------
daodantou

count(sub[,start[,end]]) 作用:查指定范围内sub字符串出现次数
代码
str1="AbcABCabCabcABCabc"
print(str1.count("ab",0,15))
------------------------------
2

find()和index()方法 用于查找子字符串在该字符串中的位置。
代码
str1="I love the life"
print(str1.find("li"))
print(str1.find("good")) #找不到 会返回-1
print(str1.index("ve"))
print(str1.index("good")) #找不到 会抛出异常
-------------------------
11
-1
4
ValueError: substring not found

join(sub) 程序员更喜欢用他来连接字符 效率要高
代码
str1=“x”.join("Test")
print(str1)
--------------------------
Txexsxt

代码
str2=“-”.join("Daodantou")
print(str2)
---------------------------
D-a-o-d-a-n-t-o-u

代码
yan = "I" + " " + "Love" + " " + "You"
print(yan)
-----------------------------------
I Love You

改进代码
yan=" ".join(["I","Love","You"]) #字符串和列表相当
print(yan)
------------------------------------
I Love You

replace(old,new[,count]) 方法如其名,替换指定字符串
str1="I Love You"
print(str1.replace("You","Daodantou"))
---------------------------------------
I Love Daodantou

split(sep=None,maxsplit=-1)用于拆分成列表,和join()相反。
代码
str1=" ".join(["I","LOVE","YOU"])
print(str1)
print(str1.split())
------------------------
I LOVE YOU
['I', 'LOVE', 'YOU']


str2="_".join("Daodantou")
print(str2)
print(str2.split(sep="_"))
--------------------------
D_a_o_d_a_n_t_o_u
['D', 'a', 'o', 'd', 'a', 'n', 't', 'o', 'u']

Daodantou:“不积跬步,无以至千里.”
原文地址:https://www.cnblogs.com/daodantou/p/10225334.html