Summary of print usage examples in Python2 and Python3, python2python3

Source: Internet
Author: User

Summary of print usage examples in Python2 and Python3, python2python3

Preface

Recently, I have been learning python, and I have been very annoyed with the print of python, which is always not output as expected. In python2, print is an output Statement, which is the same as the if statement and the while statement. In python3, to fill the various pitfalls of python2, print is changed to a function, therefore, the use of print in python3 is quite different from that in python2. Next I will give you a detailed summary of the usage of print in Python2 and Python3. I will not talk much about it. Let's take a look at the detailed introduction.

I. print usage in Python2

In Python2, print is an output statement.

strHello = 'Hello Python'print strHello# Hello Python

1. format the output integer

strHello = "the length of (%s) is %d" %('Hello Wordld', len('Hello World'))print strHello# the length of (Hello Wordld) is 11

2. format the output hexadecimal integer

# Format description # % percent mark # % c and its ASCII code # % s string # % d signed integer (decimal) # % u unsigned integer (decimal) # % o unsigned integer (octal) # % x unsigned integer (hexadecimal) # % X unsigned integer (hexadecimal in upper case) # % e floating point number (Scientific Notation) # % E floating point number (Scientific notation, replaced by e) # % f floating point number (decimal point) # % g floating point number (% e or % f based on the value) # % G floating point number (similar to % g) # % p pointer (memory address for printing value in hexadecimal format) # % n store the number of output characters in the next variable in the parameter list
nHex = 0x20print 'nHex = %x, nDec = %d, nOct = %o' %(nHex, nHex, nHex)# nHex = 20, nDec = 32, nOct = 40

To output binary data, you can use the python function bin ()

# Python 2.7.10 (default, Feb 7 2017, 00:08:15)# [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin# Type "help", "copyright", "credits" or "license" for more information.# >>> bin(789)# '0b1100010101'# >>>

3. format the output floating point number (float)

  • % Character: mark the start of the conversion specifier
  • Minimum field width: The converted string must have at least the specified width. If it is *, the width is read from the value tuples.
  • Conversion flag:-indicates left alignment; + indicates plus and minus signs must be added before the conversion value; ''(white space character) indicates that spaces are reserved before a positive number; 0 indicates that the conversion value is filled with 0 if the number of digits is not enough.
  • Point (.) followed by precision value: If the conversion is a real number, the precision value indicates the number of digits after the decimal point. If the conversion is a string, the number indicates the maximum field width. If it is *, the precision will be read from the tuples.
Import math # defaultprint 'Pi = % F' % math. pi # PI = 3.141593 # width = 10, precise = 3, align = leftprint 'Pi = % 10.3fxxx '% math. pi # PI = 3.142xxx # width = 10, precise = 3, align = rightprint 'Pi = %-10.3fxxx '% math. pi # PI = 3.142 xxx # prefill string print 'Pi = % 06d' % int (math. pi) # PI = 000003

4. format the output string (string)

# precise = 3print '%.3s' % ('jcodeer')# jco# precise = 4print '%.*s' % (4,'jcodeer')# jcod# width = 10, precise = 3print 'xx%10.3s' % ('jcodeer')# xx  jco

5. list)

l = [1, 2, 3, 'jcodeer']print l# [1, 2, 3, 'jcodeer']

6. Output dictionary)

d = {1: 'A',2: 'B',3: 'C',4: 'D'}print d# {1: 'A', 2: 'B', 3: 'C', 4: 'D'}

7. python print automatic line feed

# Print will add a carriage return at the end of the line. If you don't need it, simply add a comma ',' for I in range (): print I, #0 1 2 3 4

Or directly use the following function for output:

Import syssys. stdout. write ("output string ")

8. omnipotent % r

It can print out the following parameters as they are, with type information

formatter = '%r %r %r %r' print formatter % (1, 2, 3, 4)print formatter % ('one', 'two', 'three', 'four')print formatter % (True, False, False, True)print formatter % (formatter, formatter, formatter, formatter)print formatter % ("I had this thing.","That you could type up right.", "But it didn't sing.", "So I said goodnight.")# 1 2 3 4# 'one' 'two' 'three' 'four'# True False False True# '%r %r %r %r' '%r %r %r %r' '%r %r %r %r' '%r %r %r %r'# 'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.'

9. matrix output

import numpy as npa = np.array([[1,2],[3,4]])b = np.array([[5,6],[7,8]])print a# [[1 2]# [3 4]] print b# [[5 6]# [7 8]] print a, b# [[1 2]# [3 4]] [[5 6]# [7 8]]

Ii. print usage in Python3

Print is a function in Python3. The format () function is used to control the output format.

1. Position label

# {0} indicates the first element, {1} indicates the second element, {2} indicates the third element, and so on... A = 'ace 'B = 'hello' print ("{1}, my name is {0}". format (a, B) # hello, my name is Ace

2. Using Keyword Parameters

name = "Ace"age = 26print("{myname}'s age is {myage}".format(myname=name, myage=age))# Ace's age is 26

3. Use attributes and subscript

person = ["Ace", 26]print("{0[0]}'s age is {0[1]}".format(person))# Ace's age is 26  print("{people[0]}'s age is {people[1]}".format(people=person))# Ace's age is 26

No quotation marks are required for dictionary strings.

person = {'Ace': 26}print("{myname}'s age is {people[Ace]}".format(myname=name,people=person))# Ace's age is 26

4. format the qualifier

{0: 0. 3f} {1: 3d} can be followed by a format character, without adding %

5. Fill and align

^, <,> Represents residence, left alignment, right alignment, and back with width

a = 123.456789haha = 'haha!!!'print("{0:0.3f}, *{1:<14}*".format(a, haha))print("{0:0.3f}, *{1:>14}*".format(a, haha))print("{0:0.3f}, *{1:^14}*".format(a, haha))print("{0:0.3f}, *{1:}*".format(a, haha))  # 123.457, *haha!!!    *# 123.457, *    haha!!!*# 123.457, *  haha!!!  *# 123.457, *haha!!!*

Summary

The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

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.