python基础-字符串
字符串的各种方法
name = "adamanter Antonio Hello ALEX" # 字符串首字母大写 print(name.capitalize()) #Adamanter antonio hello alex # 字符串全部小写 print(name.casefold()) #adamanter antonio hello alex print(name.find("e")) #找到返回字母下标,找到第一个就返回了 print(name.find("sdf",3)) # 找不到false return -1 # 字符串的format格式方法,很重要,运用普遍 name0 ="my name is {},my age is {} years old" print(name0.format("alex",22)) name1 ="my name is {name},my age is {age} years old" print(name1.format(name='alex',age=22)) name2 ="my name is {name},my age is {age} years old" print(name2.format_map({'name':"alex",'age':23})) # 字符串的%格式方法,很重要,运用普遍,用%必需用s,d等表示字符串还是数字类型,而format不需要 username="ada" password="123456" print("hello123 my name is %s,my pwd is %s"%(username,password)) print("hello123 my name is {},my pwd is {}".format(username,password)) str="hello123,hello123,alex ada" print(str.center(50,"-")) #不足50字符,两侧填充- print(str.ljust(50,"-")) #不足50字符,右侧填充- print(str.rjust(50,"-")) #不足50字符,左侧填充- print(str.count("hello123")) #统计重复个数,列表也有这个方法 # 字符串拼接方法 seq=("a","b","c") print("-".join(seq)) # a-b-c # 按照逗号分割,指定分割2次 print(str.split(",",2)); # ['hello123', 'hello123', 'alex ada'] # 默认空格进行分割 print(str.split()) # 保持特殊字符原味,URL路由中用的很多 print(r"$#^&*") # 字符串替换 str123 ="hello123 world" new_str123 = str123.replace("world","python") print(new_str123) print(str123) # hello123 python # hello123 world #生成了新字符串,原字符串没有改变,所以用新改变需要新变量 list=['alex','ada','adamander'] list.append("hello") print(list) # 原列表发生了改变