博客
关于我
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/

你可能感兴趣的文章
python 字符串显示中文_Python字符串开头的b"、u"、r"与中文乱码
查看>>
Python 字符串的几种拼装方式
查看>>
python 存入数据库bigint_python基础_MySQL的bigint类型
查看>>
python 学习 面向对象编程
查看>>
Python 学习日记第三篇 -- 字典
查看>>
Python 学习笔记(一)Data type
查看>>
python 安装echarts
查看>>
python 安装opencv及问题解决
查看>>
Python 安装程序:“写入文件 C:\Python27\pythonw.exe 时出错“
查看>>
Python 安装避坑指南:从入门到进阶
查看>>
Python 安装配置详解
查看>>
python 实现儿童算术游戏
查看>>
python 实现字符串转整型
查看>>
Python 实现定时任务的八种方案!
查看>>
Python 实现自动化测试 dubbo 协议接口
查看>>
python 对json数据读取及保存与读取,对dump,dumps,load,loads的理解
查看>>
Python 对mysql数据库的操作
查看>>
Python 对象数据库列表
查看>>
Python 导入requests报错No module named requests
查看>>
python 将函数加到列表中进行调用
查看>>