跟老齐学Python之print详解
eval()
在print干事情之前,先看看这个东东。不是没有用,因为说不定某些时候要用到。
>>> help(eval) #这个是一招鲜,凡是不理解怎么用,就用这个看文档
Help on built-in function eval in module __builtin__:
eval(...)
eval(source[, globals[, locals]]) -> value
Evaluate the source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
能看懂更好了,看不懂也没有关系。看我写的吧。哈哈。概括一下,eval()是把字符串中符合python表达式的东西计算出来。意思就是:
>>> 3+4 #这是一个表达式,python会根据计算法则计算出结果来
7
>>> "3+4" #这是一个字符串,python就不计算里面的内容了,虽然里面是一个符合python规范的表达式
'3+4'
>>> eval("3+4") #这里就跟上面不一样了,就把字符串里面的表达式计算出来了
7
下面再看一个字符串“相加”的例子:
>>> "qiwsir"+".github.io"
'qiwsir.github.io'
>>> "'qiwsir'+'.github.io'" #字符串里面,python是不会进行“计算”的
"'qiwsir'+'.github.io'"
>>> eval("'qiwsir'+'.github.io'") #eval()做的事情完全不一样,它会把字符串里面的计算出来
'qiwsir.github.io'
顺便再说一下另外一个跟eval()有点类似的函数:exec(),这个函数专门来执行字符串或文件里面的python语句。
>>> exec "print 'hello, qiwsir'"
hello, qiwsir
>>> "print 'hello, qiwsir'"
"print 'hello, qiwsir'"
print详解
print命令在编程实践中用的比较多,特别是要向看看程序运行到某个时候产生了什么结果了,必须用print来输出,或者说,本讲更宽泛地说,就要说明白把程序中得到的结果输出问题。
比较简单的输出,前面已经涉及到过了:
>>> name = 'qiwsir'
>>> room = 703
>>> website = 'qiwsir.github.io'
>>> print "MY name is:%s\nMy room is:%d\nMy website is:%s"%(name,room,website)
MY name is:qiwsir
My room is:703
My website is:qiwsir.github.io
其中,%s,%d就是占位符。
>>> a = 3.1415926
>>> print "%d"%a #%d只能输出整数,int类型
3
>>> print "%f"%a #%f输出浮点数
3.141593
>>> print "%.2f"%a #按照要求输出小数位数
3.14
>>> print "%.9f"%a #如果要求的小数位数过多,后面就用0补全
3.141592600
>>> b = 3
>>> print "%4d"%b #如果是整数,这样写要求该整数占有四个位置,于是在前面增加三个空格
3 #而不是写成0003的样式
换一种范式,写成这样,就跟上面有点区别了。
>>> import math #引入数学模块
>>> print "PI=%f"%math.pi #默认,将圆周率打印成这个样子
PI=3.141593
>>> print "PI=%10.3f"%math.pi #约束一下,这个的含义是整数部分加上小数点和小数部分共计10位,并且右对齐
PI= 3.142
>>> print "PI=%-10.3f"%math.pi #要求显示的左对齐,其余跟上面一样
PI=3.142
>>> print "PI=%06d"%int(math.pi) #整数部分的显示,要求共6位,这样前面用0补足了。
PI=000003
其实,跟对上面数字操作类似,对字符串也可以做一些约束输出操作。看下面实验,最好看官也试试。
>>> website
'qiwsir.github.io'
>>> print "%.3s"%website
qiw
>>> print "%.*s"%(3,website)
qiw
>>> print "%7.3s"%website
qiw
>>> print "%-7.3s"%website
qiw
总体上,跟对数字的输出操作类似。不过,在实际的操作中,这些用的真的不是很多,至少在我这么多年的代码生涯中,用到上面复杂操作的,就是现在给列位展示的时候,充其量用一用对float类型的数据输出小数位数的操作,其它的输出操作,以默认的那种方式居多。请看官在这里鄙夷我的无知吧。
行文到此,提醒列位,如果用python3的,请用print(),要加个括号。
print有一个特点,就是输出的时候,每行后面都自动加上一个换行符号\n,这个在前面已经有所提及。
>>> website
'qiwsir.github.io'
>>> for word in website.split("."):
... print word
...
qiwsir
github
io
>>> for word in website.split("."):
... print word, #注意,加了一个逗号,输出形式就变化了吧。
...
qiwsir github io
%r是万能的吗?
我曾经说过,懒人改变世界,特别是在敲代码的领域。于是就有人问了,前面一会儿是%s,一会儿是%d,麻烦,有没有一个万能的?于是网上就有人给出答案了,%r就是万能的。看实验:
>>> import math
>>> print "PI=%r"%math.pi
PI=3.141592653589793
>>> print "Pi=%r"%int(math.pi)
Pi=3
真的是万能呀!别着急,看看这个,你是不是就糊涂了?
>>> print "Pi=%s"%int(math.pi)
Pi=3
当然,这样就肯定出错了:
>>> print "p=%d"%"pi"
Traceback (most recent call last):
File "
TypeError: %d format: a number is required, not str
如果看到这里,看官有点糊涂是很正常的,特别是那个号称万能的%r和%s,怎么都能够对原本属于%d的进行正常输出呢?
其实,不管是%r还是%s(%d)都是把做为整数的对象转化为字符串输出了,而不是输出整数。但是%r和%s是有点区别的,本讲对这个暂不做深入研究,只是说明这样的对应:%s-->str();%r-->repr(),什么意思呢?就是说%s调用的是str()函数把对象转化为str类型,而%r是调用了repr()将对象转化为字符串。关于两者的区别请参考:Difference between str and repr in Python,下面是一个简单的例子,演示一下两者区别:
>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2014, 8, 15)
>>> str(today)
'2014-08-15'
>>> repr(today)
'datetime.date(2014, 8, 15)'
最后要表达我的一个观点,没有什么万能的,一切都是根据实际需要而定。
关于更多的输出格式占位符的说明,这个页面中有一个表格,可惜没有找到中文的,如果看官找到中文的,请共享一下呀:string formatting
再扩展
>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> print "qiwsir is in %(room)d"%myinfo
qiwsir is in 703
看官是否看明白上面的输出了?有点意思。这样的输出算是对前面输出的扩展了。
出了这个扩展之外,在输出的时候,还可以用一个名曰:format的东西,这里面看不到%,但是多了{}。看实验先:
>>> print "My name is {0} and I am in {1}".format("qiwsir",703) #将format后面的内容以此填充
My name is qiwsir and I am in 703
>>> "My website is {website}".format(website="qiwsir.github.io") #{}里面那个相当于一个变量了吧
'My website is qiwsir.github.io'
看到这里,是不是感觉这个format有点意思?一点不输给前面的输出方式。据说,format会逐渐逐渐取代前面的。关于format,我计划后面一讲继续。这里只是来一个引子,后面把用format输出搞得多点。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python is better than C in development efficiency, but C is higher in execution performance. 1. Python's concise syntax and rich libraries improve development efficiency. 2.C's compilation-type characteristics and hardware control improve execution performance. When making a choice, you need to weigh the development speed and execution efficiency based on project needs.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Is it enough to learn Python for two hours a day? It depends on your goals and learning methods. 1) Develop a clear learning plan, 2) Select appropriate learning resources and methods, 3) Practice and review and consolidate hands-on practice and review and consolidate, and you can gradually master the basic knowledge and advanced functions of Python during this period.
