Learn more about the print of Python

Source: Internet
Author: User
Some basic usage of print is also involved in the previous article. This article focuses on the basis of the review and try to add as much content as possible. Eval ()

Let's take a look at this stuff before we print it. It is not useless, because it may be used in some cases.

The code is as follows:

>>> Help (eval) # This is a rare concept. if you don't understand how to use it, use this document.

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 is better to understand and understand. See what I wrote. Haha. To sum up, eval () is used to calculate a string that matches a python expression. Meaning:

The code is as follows:

>>> 3 + 4 # This is an expression. python calculates the result according to the calculation rules.
>>> "3 + 4" # This is a string. python does not calculate the content, although it is an expression conforming to the python specifications.
'3 + 4'
>>> Eval ("3 + 4") # This is different from the above. the expression in the string is calculated.

The following is an example of adding a string:

The code is as follows:

>>> "Qiwsir" + ". github. io"
'Qiwsir. github. io'
>>> "'Qiwsir '+'. github. io '" # in the string, python does not perform "computing ".
"'Qiwsir '+'. github. io '"
>>> Eval ("'qiwsir '+'. github. io '") # eval () does different things. it calculates the strings.
'Qiwsir. github. io'

By the way, another function that is a bit similar to eval (): exec () is used to execute python statements in strings or files.

The code is as follows:

>>> Exec "print 'Hello, qiwsir '"
Hello, qiwsir
>>> "Print 'Hello, qiwsir '"
"Print 'Hello, qiwsir '"

Print details

The print command is used in many programming practices. in particular, you need to use print to output the program running at a certain time, or in a broader sense, it is necessary to explain the problem of output results in the program.

Relatively simple output, as mentioned earlier:

The code is as follows:

>>> 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

Here, % s and % d are placeholders.

The code is as follows:

>>> A = 3.1415926
>>> Print "% d" % a # % d can only output integers, int type
>>> Print "% f" % a # % f output floating point number
>>> Print "%. 2f" % a # output decimal places as required
>>> Print "%. 9f" % a # if the number of decimal places required is too large, add 0 to the end.
>>> B = 3
>>> Print "% 4d" % B # if it is an integer, this write requires that the integer occupies four positions, so three spaces are added before
3 # instead of writing a 0003 style

In this way, it is a little different from the above.

The code is as follows:

>>> Import math # introduce the mathematical module
>>> Print "PI = % f" % math. pi # By default, the circumference rate is printed as this
PI = 1, 3.141593
>>> Print "PI = % 10.3f" % math. pi # constraints. this meaning is that the integer plus the decimal point and the decimal part total 10 digits, and the right alignment
PI = 1, 3.142
>>> Print "PI = %-10.3f" % math. pi # requires the left alignment of the display, and the rest are the same as above
PI = 1, 3.142
>>> Print "PI = % 06d" % int (math. pi) # display of the integer part. a total of six digits are required, so that the first digit is supplemented with 0.
PI = 1, 000003

In fact, similar to the preceding numeric operation, you can also perform some constrained output operations on strings. Take a look at the following experiment. it is best to check the official website.

The code is as follows:

>>> Website
'Qiwsir. github. io'
>>> Print "%. 3 s" % website
>>> Print "%. * s" % (3, website)
>>> Print "% 7.3 s" % website
>>> Print "%-7.3 s" % website

In general, it is similar to the number output operation. However, in actual operations, these operations are actually not much. at least during my many years of code career, I used the complex operations above, that is, when I present the column spaces, at best, we use the float type data output decimal point operation. other output operations are mostly in the default mode. Please take it easy to despise my ignorance here.

At this point, the reminder column is used. if python3 is used, use print () to add parentheses.

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

The code is as follows:

>>> Website
'Qiwsir. github. io'
>>> For word in website. split ("."):
... Print word
>>> For word in website. split ("."):
... Print word, # Note: add a comma to change the output format.
Qiwsir github io

% R is omnipotent?

I once said that lazy people change the world, especially in coding. As a result, someone asked, "% s" and "% d" are there any problems. Is there 10 thousand? So someone on the Internet gave the answer, and % r is omnipotent. Test:

The code is as follows:

>>> Import math
>>> Print "PI = % r" % math. pi
PI = 1, 3.141592653589793
>>> Print "Pi = % r" % int (math. pi)
Pi = 3

It's really omnipotent! Don't worry. look at this. are you confused?

The code is as follows:

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

Of course, an error will surely occur:

The code is as follows:

>>> Print "p = % d" % "pi"
Traceback (most recent call last ):
File" ", Line 1, in
TypeError: % d format: a number is required, not str

If you see this, it would be quite normal to look at the official website, especially the so-called omnipotent % r and % s, how can we make a normal output of the original % d?

In fact, both % r and % s (% d) convert the object as an integer into a string output instead of an output integer. However, % r is a little different from % s. I will not conduct any further research on this topic, but it just shows the corresponding: % s --> str (); % r --> repr (), what does it mean? That is to say, % s calls the str () function to convert the object to the str type, while % r calls repr () to convert the object to a string. For the differences between the two, see Difference between str and repr in Python. The following is a simple example to illustrate the differences between the two:

The code is as follows:

>>> Import datetime
>>> Today = datetime. date. today ()
>>> Today
Datetime. date (2014, 8, 15)
>>> Str (today)
>>> Repr (today)
'Datetime. date (2014, 8, 15 )'

Finally, I want to express my point of view. there is nothing to do. everything depends on actual needs.

For more information about the placeholders in the output format, there is a table on this page. Unfortunately, Chinese characters are not found. if the viewer finds a Chinese character, please share it with us: string formatting.


The code is as follows:

>>> Myinfo
{'Website': 'qiwsir. github. io ', 'name': 'qiwsir', 'Room': 703}
>>> Print "qiwsir is in % (room) d" % myinfo
Qiwsir is in 703

Do you understand the output above? A little interesting. This output is an extension of the previous output.

In addition to this extension, you can also use the name "format" when outputting the file. here, % is not displayed, but {} is added {}. Take a look at the experiment first:

The code is as follows:

>>> Print "My name is {0} and I am in {1}". format ("qiwsir", 703) # fill in the content following the format
My name is qiwsir and I am in 703
>>> "My website is {website}". format (website = "qiwsir. github. io") # {} is equivalent to a variable.
'My website is qiwsir. github. io'

Do you think this format is interesting? Do not lose to the previous output mode at all. It is said that the format will gradually replace the previous one. For the format, I plan to continue later. Here is just an introduction, and the output in format will be more detailed later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.