【冷知识】在python2.7或更早的版本中模拟类似3.x的print函数
2015-12-31 13:18
483 查看
虽然这样做没有必要因为一般情况下,我们可以有更好的方式去实现:
例如使用from __future__ import print_function来实现:
但是以下实例能帮助更好的理解print内置函数的工作方式:
例如使用from __future__ import print_function来实现:
from __future__ import print_function print(123,456,end='',file = (open('temp.txt','w')) #它大致上等价于你在2.x内写 print >>open('temp.txt','w'),123,456,
但是以下实例能帮助更好的理解print内置函数的工作方式:
# -*- coding: utf-8 -*- def print3(*args,**kargs): ''' 模拟print函数 在2.7或跟早的python版本中模拟一个能实现大部分3.x版本的print3函数 ''' import sys sep = kargs.pop('sep',' ') #字典的pop函数删除字典内指定键并返回值,如果没能找到键返回自己设置的值。 end = kargs.pop('end','\n') file = kargs.pop('file',sys.stdout) #打印流定向 if kargs: raise TypeError('extra keywords: %s'%kargs) #抛出一个异常当函数被传入其他奇怪的参数时 output = '' first = True for arg in args: output += ('' if first else sep) + str(arg) first = False file.write(output + end) #写入文件
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法