Learn Python's print

  • 2020-04-02 14:13:21
  • OfStack

The eval ()

Let's look at this guy before print does anything. It's not useless, because you might need it sometime.


>>> help(eval)      # This is a trick, anyone who doesn't understand how to use it, just use this to see the documentation 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.

It's better to be able to read, but it doesn't matter if you don't. Look what I wrote. Ha ha. To summarize, eval() evaluates what in a string corresponds to a python expression. It means:


>>> 3+4         # This is an expression, python It's going to work out the result according to the algorithm
7
>>> "3+4"       # This is a string, python I'm not going to calculate what's in there, even though it's a coincidence python Canonical expression
'3+4'
>>> eval("3+4") # So this is not the same as this, so I'm just evaluating the expression in the string
7

Here's another example of adding strings:


>>> "qiwsir"+".github.io"
'qiwsir.github.io'
>>> "'qiwsir'+'.github.io'"    # Inside the string, python You don't do the math
"'qiwsir'+'.github.io'"
>>> eval("'qiwsir'+'.github.io'") #eval() It's going to do something completely different, and it's going to compute what's in the string
'qiwsir.github.io'

By the way, there's another function similar to eval() : exec(), which executes python statements in strings or files.


>>> exec "print 'hello, qiwsir'"
hello, qiwsir
>>> "print 'hello, qiwsir'"
"print 'hello, qiwsir'"

Print,

The print command is used a lot in programming practice, especially to see what results are produced when the program runs to a certain point, so you have to use print to print, or, more broadly in this lecture, to explain the output of the results in the program.

The simpler output, which has been covered previously:


>>> name = 'qiwsir'
>>> room = 703
>>> website = 'qiwsir.github.io'
>>> print "MY name is:%snMy room is:%dnMy website is:%s"%(name,room,website)
MY name is:qiwsir
My room is:703
My website is:qiwsir.github.io

Where %s and %d are placeholders.


>>> a = 3.1415926
>>> print "%d"%a    #%d Can only output integers ,int type
3
>>> print "%f"%a  #%f Output floating point
3.141593
>>> print "%.2f"%a # Output decimals as required
3.14
>>> print "%.9f"%a  # If you want too many decimal places, you use them later 0 completion
3.141592600
>>> b = 3         
>>> print "%4d"%b   # If it is an integer, write this so that the integer occupies four positions, adding three Spaces in front of it
   3                # Instead of writing 0003 The style of the

If I were to change the normal form and write it like this, it would be a little bit different.


>>> import math     # Introduction of mathematical module
>>> print "PI=%f"%math.pi # By default, PI is printed like this
PI=3.141593
>>> print "PI=%10.3f"%math.pi # So by constraint, this means that the integer part plus the decimal point and the decimal part add up 10 Bit, and right aligned
PI=     3.142
>>> print "PI=%-10.3f"%math.pi # Left alignment is required, and the rest is the same as above
PI=3.142
>>> print "PI=%06d"%int(math.pi) # Integer part of the display, total requirements 6 position , In front of it 0 Make up for.
PI=000003

In fact, just like with the Numbers above, you can do some constrained output with strings. See the experiment below, had better look at the official also try.


>>> website
'qiwsir.github.io'
>>> print "%.3s"%website
qiw
>>> print "%.*s"%(3,website)
qiw
>>> print "%7.3s"%website
    qiw
>>> print "%-7.3s"%website
qiw   

In general, it is similar to the output operation of a number. However, in actual operation, the use of really isn't a lot, at least in my code career for so many years, using complex operation above, is now show was complete when, at best, use to the operation of the float type of data output decimal digits, the output of other operations, in the majority with the default that way. Please see the judge here despise my ignorance.

Okay, so this is where the line goes, and I'm going to remind the column bit that if you're using python3, you're going to use print(), and you're going to put a parenthesis.

Print has a feature that when output, each line is automatically followed by a newline symbol \n, which has been mentioned before.


>>>  website
'qiwsir.github.io'
>>> for word in website.split("."):
...     print word
...
qiwsir
github
io
>>> for word in website.split("."):
...     print word,         # Notice that when you add a comma, the output changes.
...
qiwsir github io

Is %r universal?

I've said that lazy people change the world, especially in the area of coding. So someone asked, in front of a moment is %s, a moment is %d, trouble, there is a universal? So someone on the Internet came up with the answer: %r is the answer. The experiment:


>>> import math
>>> print "PI=%r"%math.pi
PI=3.141592653589793
>>> print "Pi=%r"%int(math.pi)
Pi=3

Really is omnipotent! Don't worry, look at this, are you confused?


>>> print "Pi=%s"%int(math.pi)
Pi=3

Of course, that would be a mistake:


>>> print "p=%d"%"pi"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: %d format: a number is required, not str

If you see here, it is normal to be a little confused, especially the so-called omnipotence of %r and %s, how can the original belongs to the normal output of %d?

In fact, both %r and %s(%d) output the object as an integer as a string, not an integer. But %r and %s are somewhat different, this lecture on this temporarily do not do in-depth research, just to explain the correspondence: %s > STR (); % r - > Repr of alpha, what does that mean? That is, %s calls the STR () function to convert the object to a STR type, and %r calls the repr() function to convert the object to a string. For the Difference between STR and repr in Python, here is a simple example to illustrate the Difference:


>>> import datetime
>>> today = datetime.date.today()
>>> today
datetime.date(2014, 8, 15)
>>> str(today)
'2014-08-15'
>>> repr(today)
'datetime.date(2014, 8, 15)'

Finally, I would like to express my point that there is no one-size-fits-all, everything is according to the actual needs.

For more explanation of output format placeholder, there is a table in this page, but it is a pity that I did not find the Chinese one. If you find the Chinese one, please share it: string formatting

To extend the


>>> myinfo
{'website': 'qiwsir.github.io', 'name': 'qiwsir', 'room': 703}
>>> print "qiwsir is in %(room)d"%myinfo
qiwsir is in 703

Do you see the output? Kind of interesting. This output is an extension of the previous output.

Out of this extension, when the output, you can also use a name: format thing, which can not see %, but more {}. Look at the experiment first:


>>> print "My name is {0} and I am in {1}".format("qiwsir",703)     # will format Fill in the rest
My name is qiwsir and I am in 703
>>> "My website is {website}".format(website="qiwsir.github.io")    #{} The inside one is equivalent to a variable
'My website is qiwsir.github.io'

See here, is this format a little bit interesting? No less than the previous output. It is said that format will gradually replace the previous one. I plan to continue with format in the next lecture. Here is just a lead, followed by the format output more.


Related articles: