str9 = "sunck is a good man!" str10 = str9[6:15] print(str10) # is a good
截取字符串的全部字符
1 2
str10 = str9[:] print(str10) # sunck is a good man!
从头开始截取
1 2
str10 = str9[:5] print(str10) # sunck
从给定下标处开始截取到结尾
1 2
str10 = str9[16:] print(str10) # man!
截取倒数第一个字符
1 2
str10 = str9[-1] print(str10) # !
创造一个与原字符串顺序相反的字符串
1 2
str10 = str9[::-1] print(str10) # !nam doog a si kcnus
逆序截取
1 2
str10 = str9[:-5:-3] print(str10) # !m
判断是否存在
1 2 3
str11 = "sunck is a good man!" print("good"in str11) # True print("good1"notin str11) # True
格式化输出
1 2 3 4 5
num = 10 f = 3.1415923635 print("num =", num) # 会四舍五入 num = 10 print("num = %d str11 = %s f = %.10f" % (num, str11, f)) # num = 10 str11 = sunck is a good man! f = 3.1415923635
转义字符
转换成有特殊含义的字符
\n 换行
1 2 3 4 5 6 7 8 9 10
print("num = %d\nstr11 = %s\nf = %.10f" % (num, str11, f)) """ num = 10 str11 = sunck is a good man! f = 3.1415923635 """ print("suck \\n is") # suck \n is
print('tom is \'good\' man') # tom is 'good' man print("tom is 'good' man") # tom is 'good' man
如果字符串内有很多换行,用\n写在一行不好阅读
1 2 3 4 5 6 7 8 9 10 11 12 13 14
print("good\nman\nhandsome") """ good man handsome """ print("""good man handsome""") """ good man handsome """
str12 = "SUNCK is a good man" print(str12.lower()) # sunck is a good man
str.upper():转换字符串中的小写字母为大写字母
1 2 3 4
print(str12.upper()) # SUNCK IS A GOOD MAN print("sunck is a good man".upper()) # SUNCK IS A GOOD MAN
print("原字符串", str12) # 原字符串 SUNCK is a good man
str.swapcase(): 大写变小写 小写变大写
1
print("SuNcK iS a GoOd MaN".swapcase()) # sUnCk Is A gOoD mAn
str.capitalize() 首字母大写 其他字母小写
1
print("SuNcK iS a GoOd MaN".capitalize()) # Sunck is a good man
str.title(): 每个首字母大写 其他字母小写
1
print("SuNcK iS a GoOd MaN".title()) # Sunck Is A Good Man
str.center(width,fillchar)
width: 返回一个指定宽度的居中字符串
fillchar: 填充的字符串(默认为空格填充)
1
print("SuNcK iS a GoOd MaN".center(25, "*")) # ***SuNcK iS a GoOd MaN***
str.ljust(width[,fillchar])
width: 返回一个指定宽度的左对齐字符串
fillchar: 填充的字符串(默认为空格填充)
1
print("SuNcK iS a GoOd MaN".ljust(25, "%")) # SuNcK iS a GoOd MaN%%%%%%
str.rjust(width[,fillchar])
width: 返回一个指定宽度的右对齐字符串
fillchar: 填充的字符串(默认为空格填充)
1
print("SuNcK iS a GoOd MaN".rjust(25, "%")) # %%%%%%SuNcK iS a GoOd MaN
str.zfill(width)
返回一个长度为width的字符串,原字符串右对齐,前面补0
1
print("SuNcK iS a GoOd MaN".zfill(25)) # 000000SuNcK iS a GoOd MaN
str.count(str[,start][,end])
返回指定字符串str出现的次数 默认从头到尾
1
print("ha Very Very is a man ,ha ha ha".count("Very", 3, 12)) # 2
str.find(str[,start][,end])
从左向右检测str字符串是否包含在字符串中 默认从头到尾 得到第一次出现返回的下标 没有返回-1
1 2 3
print("ha Very Very is a man ,ha ha ha".find("Very")) # 3 print("ha Very Very is a man ,ha ha ha".find("Good")) # -1 print("ha Very Very is a man ,ha ha ha".find("Very", 7)) # 8
str.rfind(str[,start][,end])
从右向左检测str字符串是否包含在字符串中 得到第一次出现返回的下标 没有返回-1
1 2 3
print("ha Very Very is a man ,ha ha ha".rfind("Very")) # 8 print("ha Very Very is a man ,ha ha ha".rfind("Good")) # -1 print("ha Very Very is a man ,ha ha ha".rfind("Very", 7)) # 8
str.index(str[,start][,end])
和find()一样 不过str不存在时会报异常
1
print("ha Very Very is a man ,ha ha ha".index("Very")) # 3
str.rindex(str[,start][,end])
和rfind()一样 不过str不存在时会报异常
1
print("ha Very Very is a man ,ha ha ha".rindex("Very")) # 8
lstrip(): 截取字符串左侧指定的字符 默认为空格
1 2
print("************ha Very Very is a man ,ha ha ha".lstrip("*")) # ha Very Very is a man ,ha ha ha
rstrip(): 截取字符串右侧指定的字符 默认为空格
1 2
print("ha Very Very is a man ,ha ha ha************".rstrip("*")) # ha Very Very is a man ,ha ha ha
strip()截取字符串左右指定的字符 默认为空格
1 2 3 4 5 6 7
print("***********ha Very Very is a man ,ha ha ha***********".strip("*")) # ha Very Very is a man ,ha ha ha
str = "a" print(ord(str)) # 97 print(chr(65)) # A print("a" == "a") # true
str13 = "sunck**is******a***good*man" list1 = str13.split("*") print(list1) # ['sunck', '', 'is', '', '', '', '', '', 'a', '', '', 'good', 'man'] c = 0 for s in list1: iflen(s) > 0: c += 1 print(c) # 5
splitlines([keepends]) 按照(‘\r’,’\r\n’,’\n’)分隔
keepends == True 会保留换行符
1 2 3 4 5 6
str14 = """sunck is a good man! sunck is a nice man! sunck is a handsome man! """ print(str14.splitlines()) # ['sunck is a good man!', 'sunck is a nice man!', 'sunck is a handsome man!']
join() : 以指定的字符串分隔符,将seq中的所有元素组合成一个字符串
1 2 3
list2 = ['sunck', 'is', 'a', 'good', 'man'] str15 = " ".join(list2) print(str15) # sunck is a good man
max() min() 最大值和最小值
1 2 3
str16 = "sunck is a good man!z" print(max(str16)) # z print("*" + min(str16) + "*") # 是一个空格 * *
replace(oldstr,newstr,count)
用newstr替换oldstr,默认是全部替换,如果指定了count,那么只替换前count个
1 2 3 4
str17 = "sunck is a good good good man!" str18 = str17.replace("good", "nice", 1) print(str17) # sunck is a good good good man! print(str18) # sunck is a nice good good man!
创建一个字符串映射表
参数:要转换的字符串 目标字符串
1 2 3 4 5
t19 = str.maketrans("ac", "65") # a--6 c--5 str20 = "sunck is a good man!" str21 = str20.translate(t19) print(str21) # sun5k is 6 good m6n!
startswith(str,start=0,end=len(str))
在给定范围内判断是否以str开头,没有指定范围,默认为整个字符串
1 2
str22 = "sunck is a good man!" print(str22.startswith("sunck", 5, 16)) # False
endswith(str,start=0,end=len(str))
在给定范围内判断是否以str结尾,没有指定范围,默认为整个字符串
1 2
str22 = "sunck is a good man!" print(str22.endswith("man", 5, 16)) # False
encode(encoding="utf-8",errors="strict") 编码
注意:要与编码时的编码格式一致
str23 = "sunck is a good man凯!"
ignore 忽略错误
1 2 3
data52 = str23.encode("utf-8", "ignore") print(data52) # b'sunck is a good man\xe5\x87\xaf!' print(type(data52)) # <class 'bytes'>
解码
1 2
str24 = data52.decode("gbk", "ignore") print(str24) # sunck is a good man鍑!
isalpha()
如果字符串中至少有一个字符且所有字符都是字母返回True,否则返回False
1 2
str25 = "sunck is a good man!" print(str25.isalpha()) # False
""" list = [Expression for var in range] 参数说明: list:列表名称 Expression:表达式,用于计算新列表的元素 var:循环变量 range:采用range()函数生成的range对象 """ multiples = [i for i inrange(30) if i % 3is0] print(multiples) # [0, 3, 6, 9, 12, 15, 18, 21, 24, 27] print(type(multiples)) # <class 'list'>
zip
将多个列表对应位置的元素组合成为元组,并返回这个zip对象
1 2 3 4 5 6
a = [10, 20, 30] b = [40, 50, 60] c = [70, 80, 90] d = zip(a, b, c) print(d) # <zip object at 0x000001A33C7EF248> print(list(d)) # [(10, 40, 70), (20, 50, 80), (30, 60, 90)]
for key in dict1: print(key, dict1[key]) # lilei 80
for value in dict1.values(): # [80,99] print(value) # 80 ## 使用字典对象的items()方法可以获取字典的“键值对”列表 ## print(dict1.items()) for k, v in dict1.items(): print(k, v) # lilei 80
for i, v1 inenumerate(dict1): print(i, v1) # 0 lilei
字典推导式
大小写key合并
1 2 3 4 5 6 7
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} mcase_frequency = { k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys() if k.lower() in ['a', 'b'] } print(mcase_frequency) # {'a': 17, 'b': 34}
快速更换key和value
1 2 3
mcase = {'a': 10, 'b': 34} mcase_frequency = {v: k for k, v in mcase.items()} print(mcase_frequency) # {10: 'a', 34: 'b'}
和list比较
查找和插入的速度极快,不会随着key-value的增加而变慢
需要占用大量的内存,内存浪费多
list
查找和插入会随着数据量的增加而变慢
占用空间小,浪费内存少
1 2 3 4 5 6 7 8
w = input("请输入一个字符串:")
## w = "good"
str1 = "sunck is a good man!sunck is a nice man!sunck is a hands man!sunck is a good man!" \ "sunck is a good man!sunck is a nice man!sunck is a great man!sunck is a noble man!" \ "sunck is a cool man!" print("字符串%s出现" % w, str1.count(w), "次")
age = int(input("请输入一个年龄:")) if age < 0: print("未出生") elif age <= 3: print("婴儿") elif age <= 6: print("儿童") elif age <= 18: print("青少年") elif age <= 30: print("青年") elif age <= 40: print("壮年") elif age <= 50: print("中年") elif age <= 100: print("老年") elif age <= 150: print("老寿星") else: print("老妖怪")
num = 1 while num <= 5: print(num) num += 1 """ 1 2 3 4 5 """
## 计算1+2+3+……+100 sum = 0 num = 1 while num <= 100: sum += num num += 1 print("sum = %d" % (sum)) # sum = 5050
str = "zykj" index = 0 while index < len(str): print("str[%d] = %s" % (index, str[index])) index += 1 """ str[0] = z str[1] = y str[2] = k str[3] = j """
死循环:表达式永远为真
1 2
while1: print("hello world")
1 2 3 4 5 6
while else 语句:
while 表达式: 语句1 else: 语句2
1 2 3 4 5 6
a = 1 while a <= 3: print("hello world") a += 1 else: print("very very good")
for 语句
1 2 3 4
for 语句 格式: for 变量名 in 集合: 语句
1 2 3 4 5 6 7 8 9
for i in [1, 2, 3, 4, 5]: print(i) """ 1 2 3 4 5 """