博客
关于我
python基础知识(3)
阅读量:168 次
发布时间:2019-02-28

本文共 1837 字,大约阅读时间需要 6 分钟。

Python字符串处理与迭代控制

去除字符串首尾空格

去除字符串首尾空格有两种常用方法:

方法一:切片操作

str = ' abcde 'print(str[1:len(str)-1])

方法二:strip()方法

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/

你可能感兴趣的文章
Python3之写入Excel文档(xlsxwriter)
查看>>
Python3之打印操作打印流重定向(下)
查看>>
python3判断字典、列表、元组为空以及字典是否存在某个key的方法
查看>>
Python3利用pymysql操作 MySQL
查看>>
python3处理json文件中含有中文dumps的应用
查看>>
Python3子进程输出
查看>>
Python3学习笔记3,变量、运算符
查看>>
Python3学习笔记(urllib模块的使用)
查看>>
python3安装scapy_Linux下安装scapy-python3
查看>>
python3实现socket通信
查看>>
Python关于numpy.transpose函数详细解析附代码
查看>>
Python3导入自定义模块的3种方式
查看>>
python3打开txt文件_使用Python 3从文本文件读取句子并添加到列表中
查看>>
python3爬虫抓取智联招聘职位信息代码
查看>>
Python3爬虫数据入数据库---把爬取到的数据存到数据库,带数据库去重功能
查看>>
python3的 pymysql把mysqldb库取代了,让python 3支持mysqldb的解决方法
查看>>
Python3笔记——IDE的选择
查看>>
python3简单使用requests 用户代理,cookie池
查看>>
Python3组播通信编程实现教程(发送者+接收者)
查看>>
Python3编写网络爬虫10-数据存储方式三-CSV文件存储
查看>>