本文共 1837 字,大约阅读时间需要 6 分钟。
去除字符串首尾空格有两种常用方法:
str = ' abcde 'print(str[1:len(str)-1])
strip()方法可以去除字符串的首尾空格,但不能去除中间空格。
str.strip([chars]); # 移除字符串头尾指定的字符序列str = "00000003210Runoob01230000000"; print(str.strip('0')); # 去除首尾字符0str2 = " Runoob "; print(str2.strip()); # 去除首尾空格 在Python中,迭代是通过for ... in来完成的。以下是常见迭代对象的操作方法:
d = {'a': 1, 'b': 2, 'c': 3}for key in d: print(key)# 输出:a b cfor value in d.values(): print(value)# 输出:1 2 3for k, v in d.items(): print(k, v)# 输出:a 1 b 2 c 3 lst = ['acd', 'def', 'ghr']for i in lst: print(i)# 输出:acd def ghrfor i in range(len(lst)): print(i)# 输出:0 1 2for item in enumerate(lst): print(item[0], item[1])# 输出:0 acd 1 def 2 ghr
列表生成式是一种简洁高效的数据生成方式。
num_list = list(range(1, 11))print(num_list)# 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
l = []for i in range(1, 11): l.append(i * i) print(l)# 输出:# [1]# [1, 4]# [1, 4, 9]# [1, 4, 9, 16]# [1, 4, 9, 16, 25]# [1, 4, 9, 16, 25, 36]# [1, 4, 9, 16, 25, 36, 49]# [1, 4, 9, 16, 25, 36, 49, 64]# [1, 4, 9, 16, 25, 36, 49, 64, 81]# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]l = [i * i for i in range(1, 5)]print(l)# 输出:[1, 4, 9, 16]
sorted()方法是一个强大的高阶函数,可用于对各种可迭代对象进行排序。
sorted_list = sorted([36, 5, -12, 9, -21])print(sorted_list)# 输出:[-21, -12, 5, 9, 36]
sorted_list = sorted([36, 5, -12, 9, -21], key=abs)print(sorted_list)# 输出:[5, 9, -12, -21, 36]
sorted_str = sorted(['bob', 'about', 'Zoo', 'Credit'])print(sorted_str)# 输出:['about', 'bob', 'Credit', 'Zoo']sorted_str = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)print(sorted_str)# 输出:['about', 'bob', 'Credit', 'Zoo']sorted_str = sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)print(sorted_str)# 输出:['Zoo', 'Credit', 'bob', 'about']
通过这些方法,可以轻松地对各种数据进行排序,满足不同场景的需求。
转载地址:http://apnj.baihongyu.com/