""" # 字符串索引与切片 # 字符串所有的操作都不会改变原来的字符串,只会生成新的字符串 s = "ABCDEFGHIGKLM" s1 = s[0] print(s1) # 顾头不顾尾 字符串切片 s2 = s[0:2] print(s2) s3 = s[:] # 获取所有的字符串 print(s3) s4 = s[::-1] # 取反都要加-1 print(s4) s5 = s[::3] # [首:尾:步长] print(s5) s6 = s[::-2] print(s6) s7 = s[4:0:-2] print(s7) """ # 字符串相关操作 name = "break Dyj" # 首字母大写 str1 = name.capitalize() print(str1) # 全大写,全小写 str2 = name.upper() str3 = name.lower() print(str2, str3) # 大小写翻转 str4 = name.swapcase() print(str4) # 头部大写 特殊字符分开的都会大写 (数字也是特殊字符) str5 = "my-name/is*break" str6 = str5.title() print(str6) # 左右加填充物 str7 = "Break" str8 = str7.center(21, "-") print(str8) # 没满8位的,会把前面的位置全部加上补全八位,满了八位会补全16位 str9 = "BBBBBBBBBB\tak" print(str9) str10 = str9.expandtabs() print(str10) # 以什么为开头 区分大小写 (字符串,开始,结束) str11 = str7.startswith(‘Break‘, 0, 5) print(str11) # 通过元素找索引 找得到返回索引,找不到返回-1->find # 通过元素找索引 找得到返回索引,找不到会报错->index _int = str9.index("B") _int2 = str9.find("B") print(_int,_int2) # strip rstrip lstrip ->左右同时删 只删右边 只删左边 str12 = "Break" str13 = str12.strip("B") print(str13) # 查找字符串个数 str14 = str9.count("BBB", 2, 5) print(str14) # 字符串分割 str15 = "B,R,E,A,K" list = str15.split(",") print(list) # format的三中玩法 格式化输出 s = "我叫{},今年{}岁,爱好{},再说一遍,我叫{}".format("Break",19,"girl","Break") print(s) s = "我叫{0},今年{1}岁,爱好{2},再说一遍,我叫{0}".format("Break", 19, "girl") # 里面写索引 print(s) # name = input("请输入你的名字:") s = "我叫{name},今年{age}岁,爱好{hobby},再说一遍,我叫{name}".format(name=name, age=19, hobby="girl") print(s) # 字符串替换 str_ = "w了肯德基奥斯卡里面的拉斯科目达拉斯肯德基" str_1 = str_.replace("肯德基", "Break", 1) # old new num 默认全部替换 print(str_1) # is系列 _str = "asdjnasjk1118564" print(_str.isalnum()) # 字符串是否是由字母和数组组成 print(str_.isdigit()) # 字符串是否是由数字组成 print(str_.isalpha()) # 字符串是否是由字母组成 t = "手机卡湖南大家看的苍井空" if "苍井空" in t: print("您输入的字符含有敏感词汇...") for i in t: print(i)
原文地址:https://www.cnblogs.com/breaki/p/9194791.html
时间: 2024-10-29 19:43:19