版权声明:xuhaha©2018 https://blog.csdn.net/weixin_42793426/article/details/82757838
Python List append()方法
描述
append() 方法用于在列表末尾添加新的对象。
语法
append()方法语法:
list.append(obj)
参数
- obj -- 添加到列表末尾的对象。
返回值
该方法无返回值,但是会修改原来的列表。
实例
以下实例展示了 append()函数的使用方法:
#!/usr/bin/python
aList = [123, 'xyz', 'zara', 'abc'];
aList.append( 2009 );
print "Updated List : ", aList;
以上实例输出结果如下:
Updated List : [123, 'xyz', 'zara', 'abc', 2009]
Python File flush() 方法
概述
flush() 方法是用来刷新缓冲区的,即将缓冲区中的数据立刻写入文件,同时清空缓冲区,不需要是被动的等待输出缓冲区写入。
一般情况下,文件关闭后会自动刷新缓冲区,但有时你需要在关闭前刷新它,这时就可以使用 flush() 方法。
语法
flush() 方法语法如下:
fileObject.flush();
参数
-
无
返回值
该方法没有返回值。
实例
以下实例演示了 flush() 方法的使用:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("runoob.txt", "wb")
print "文件名为: ", fo.name
# 刷新缓冲区
fo.flush()
# 关闭文件
fo.close()
以上实例输出结果为:
文件名为: runoob.txt
Python File seek() 方法
概述
seek() 方法用于移动文件读取指针到指定位置。
语法
seek() 方法语法如下:
fileObject.seek(offset[, whence])
参数
-
offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
-
whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
返回值
该函数没有返回值。
实例
以下实例演示了 readline() 方法的使用:
文件 runoob.txt 的内容如下:
1:www.runoob.com
2:www.runoob.com
3:www.runoob.com
4:www.runoob.com
5:www.runoob.com
循环读取文件的内容:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 打开文件
fo = open("runoob.txt", "rw+")
print "文件名为: ", fo.name
line = fo.readline()
print "读取的数据为: %s" % (line)
# 重新设置文件读取指针到开头
fo.seek(0, 0)
line = fo.readline()
print "读取的数据为: %s" % (line)
# 关闭文件
fo.close()
以上实例输出结果为:
文件名为: runoob.txt
读取的数据为: 1:www.runoob.com
读取的数据为: 1:www.runoob.com
Python endswith()方法
描述
Python endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。
语法
endswith()方法语法:
str.endswith(suffix[, start[, end]])
参数
- suffix -- 该参数可以是一个字符串或者是一个元素。
- start -- 字符串中的开始位置。
- end -- 字符中结束位置。
返回值
如果字符串含有指定的后缀返回True,否则返回False。
实例
以下实例展示了endswith()方法的实例:
#!/usr/bin/python
str = "this is string example....wow!!!";
suffix = "wow!!!";
print str.endswith(suffix);
print str.endswith(suffix,20);
suffix = "is";
print str.endswith(suffix, 2, 4);
print str.endswith(suffix, 2, 6);
以上实例输出结果如下:
True
True
True
False
Python range() 函数用法
python range() 函数可创建一个整数列表,一般用在 for 循环中。、
range(start, stop[, step])
参数说明:
- start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
- stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
- step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
以下是 range 在 for 中的使用,循环出runoob 的每个字母:
>>>x = 'runoob'
>>> for i in range(len(x)) :
... print(x[i])
...
r
u
n
o
o
b
>>>