python函数连载教程 python liao( 三 )


var1 = 'Hello World!'
var2 = "Python Runoob"
print "var1[0]: ", var1[0]
print "var2[1:5]: ", var2[1:5]
转义字符
格式化输出
print "My name is %s and weight is %d kg!" % ('Zara', 21)
字符串函数:
添加元素
list = []## 空列表
list.append('Google')## 使用 append() 添加元素
list.append('Runoob')
print list
删除元素
list1 = ['physics', 'chemistry', 1997, 2000]
print list1
del list1[2]
print "After deleting value at index 2 : "
print list1
列表操作
列表方法
删除字典
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
del dict['Name']; # 删除键是'Name'的条目
dict.clear();# 清空词典所有条目
del dict ;# 删除词典
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
字典的函数:
当前时间戳:
import time
time.time()
格式化日期输出
import time
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print time.strftime("%a %b %d %H:%M:%S %Y", time.localtime())
a = "Sat Mar 28 22:24:24 2016"
print time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y"))
获取某个月日历:calendar
import calendar
cal = calendar.month(2016, 1)
print "以下输出2016年1月份的日历:"
print cal
当前日期和时间
import datetime
i = datetime.datetime.now()
print ("当前的日期和时间是 %s" % i)
print ("ISO格式的日期和时间是 %s" % i.isoformat() )
print ("当前的年份是 %s" %i.year)
print ("当前的月份是 %s" %i.month)
print ("当前的日期是%s" %i.day)
print ("dd/mm/yyyy 格式是%s/%s/%s" % (i.day, i.month, i.year) )
print ("当前小时是 %s" %i.hour)
print ("当前分钟是 %s" %i.minute)
print ("当前秒是%s" %i.second)
不定长参数:*
lambda:匿名函数
def....
python模块搜索路径
获取用户输入
str = raw_input("请输入:")
print "你输入的内容是: ", str
input可以接收表达式
open参数
write要自己添加换行符
读取10个字符
重命名:os.rename
os.remove
os.mkdiros.chdir
os.getcwd
os.rmdir
open参数
file的方法
异常:
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
except IOError:
print "Error: 没有找到文件或读取文件失败"
else:
print "内容写入文件成功"
fh.close()
try:
fh = open("testfile", "w")
fh.write("这是一个测试文件,用于测试异常!!")
finally:
print "Error: 没有找到文件或读取文件失败"
用户自定义异常:
os模块提供了非常丰富的方法用来处理文件和目录 。常用的方法如下表所示:
| 序号 | 方法及描述 |
| 1 |
os.access(path, mode)
检验权限模式 |
| 2 |
os.chdir(path)
改变当前工作目录 |
| 3 |
os.chflags(path, flags)
设置路径的标记为数字标记 。|
| 4 |
os.chmod(path, mode)
更改权限 |
| 5 |
os.chown(path, uid, gid)
更改文件所有者 |
| 6 |
os.chroot(path)
改变当前进程的根目录 |
| 7 |
os.close(fd)
关闭文件描述符 fd |
| 8 |
os.closerange(fd_low, fd_high)
关闭所有文件描述符 , 从 fd_low (包含) 到 fd_high (不包含), 错误会忽略 |
| 9 |
os.dup(fd)
复制文件描述符 fd |
| 10 |
os.dup2(fd, fd2)
将一个文件描述符 fd 复制到另一个 fd2 |
| 11 |
os.fchdir(fd)

推荐阅读