python学习记录(三),,0827--http
python学习记录(三),,0827--http
0827--https://www.cnblogs.com/fnng/archive/2013/02/24/2924283.html
通用序列操作
索引
序列中的所有元素都是有编号的--从0开始递增。这些元素可以通过编号分别访问。
>>> test = ‘testdemo‘>>> test[0]‘t‘>>> test[4]‘d‘
使用负数索引时,Python会从最后一个元素开始计数,注意:最后一个元素的位置编号是-1
>>> test = ‘testdemo‘>>> test[-1]‘o‘>>> test[-2]‘m‘
或者直接在字符串后使用索引
>>>‘testdemo‘[0]
‘t‘
>>>‘testdemo‘[-1]
‘o‘
如果一个函数调用返回一个序列,那么可以直接对返回结果进行索引操作。
>>> fourth = input(‘year:‘)[3]year:2013>>> fourth‘3‘
分片
与使用索引来访问单个元素类似,可以使用分片操作来访问一琮范围内的元素。分片通过冒号相隔的两个索引来实现
>>> tag = ‘<a href="http://www.python.org">Python web site</a>‘>>> tag[9:30] # 取第9个到第30个之间的字符‘http://www.python.org‘>>> tag[32:-4] #取第32到第-4(倒着数第4个字符)‘Python web site‘
如果求10个数最后三个数:
>>> numbers = [0,1,2,3,4,5,6,7,8,9]>>> numbers[7:-1] # 从第7个数到 倒数第一个数[7, 8] #显然这样不可行>>> numbers[7:10] #从第7个数到第10个数[7, 8, 9] #这样可行,索引10指向的是第11个元素。>>> numbers[7:] # 可以置空最后一个索引解决[7, 8, 9]>>> numbers[:3] [0, 1, 2]>>> numbers[:][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
对URL进行分割
# 对http://www.baidu.com形式的URL进行分割url = raw_input(‘Please enter the URL:‘)domain = url[10:-4]print "Domain name:" + domain
--------------------------------------------------------------------
输入
>>> Please enter the URL:http://www.baidu.com输出:Domain name:baidu
步长
>>> numbers = [0,1,2,3,4,5,6,7,8,9]>>> numbers[0:10:1] #求0到10之间的数,步长为1[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> numbers[0:10:2] #步长为2[0, 2, 4, 6, 8]>>> numbers[0:10:3] #步长为3[0, 3, 6, 9]
序列相加
通过使用加号可以进行序列的连接操作
>>> ‘python ‘ * 5‘python python python python python ‘>>> [25] * 10[25, 25, 25, 25, 25, 25, 25, 25, 25, 25]
如果想创建一个占用十个元素空间,却不包括任何有用的内容的列表,可以用Nome
>>> sequence = [None] * 10>>> sequence[None, None, None, None, None, None, None, None, None, None]
序列(字符串)乘法示例:
# 以正确的宽度在居中的“盒子”内打印一个句子# 注意,整数除法运算符(//)只能用在python 2.2 以及后续版本,在之前的版本中,只能用普通除法(/)sentence = raw_input("Sentence : ")screen_width = 80text_width = len(sentence)box_width = text_width + 6left_margin = (screen_width - box_width) //2printprint ‘ ‘ * left_margin + ‘+‘ + ‘-‘ * (box_width - 2)+ ‘+‘print ‘ ‘ * left_margin + ‘| ‘ + ‘ ‘ * text_width + ‘ |‘print ‘ ‘ * left_margin + ‘| ‘ + sentence + ‘ |‘print ‘ ‘ * left_margin + ‘| ‘ + ‘ ‘ * text_width + ‘ |‘print ‘ ‘ * left_margin + ‘+‘ + ‘-‘ * (box_width - 2)+ ‘+‘
-------------------------------------------------------------------------------------------------------------------
结果
长度、最小值和最大值
内建函数len、min和max非常有用。Len函数返回序列中所包含元素的数量。Min函数和max函数则分别返回序列中最大和最小的元素。
>>> numbers = [100,34,678]>>> len (numbers)3>>> max(numbers)678>>> min(numbers)34>>> max(2,3)3>>> min(9,3,2,5)2
python学习记录(三)
相关内容
- 【小白Python学习】成绩雷达图,, 1 import
- Python网络编程_TCP(简略版),,TCP监听套接字:
- Python文件操作大全,,Python 编程文
- Python实战练习——打印日历教程,,很长一段时间没有接
- 分享《流畅的Python》(官方高清中文版PDF+高清英文版
- Python入门5(pandas中merge中的参数how),, 1 import
- 用Python爬取28010条《隐秘的角落》评论,有没发现点什
- Python画三维图-----插值平滑数据,,一、二维的插值方法
- Python中的turtle初探,,turtlePyth
- 服务器创建Python虚拟环境,,三、创建Python
评论关闭