Home Swift UNIX C Assembly Go Web MCU Research Non-Tech

How output data in Python

2022-06-03 | Web | #Words: 1565 | 中文原版

There are two types of output data formats: formatted output and direct output. For example, the f of printf function in C language means formatted. Different data types can be printed through conversions such as %d. Python also has two types.

In generally, str() and print() functions are used for direct output (not only for direct output); there are many types of formatted output, we will talk about it later.

Direct output

There are some ways to directly output:

Expression

The results can be output directly through expressions, as follows:

>>> 1+1
2

str()

str() will directly output the content in parentheses as a string. as follows:

>>> str(b'Zoot!')
"b'Zoot!'"

print()

print() output in stringformat:

# Output number
>>> print(123)
123
# Output string
>>> print("abc")
abc
# Output three variables at once with commas separated, then the output values ​​will be separated by space
>>> a=1
>>> b=2
>>> c="abc"
>>> print(a,b,c)
1 2 abc
# Output two values at once with commas separated, the output string will be separated by space 
>>> print("Hello","World!")
Hello World!
# Output two values at once, but without commas separating them, the output strings will be concatenated, no any separator
>>> print("Hello""World!")
HelloWorld!
# Output two values at once with commas separated, and set the separator to a period, then the output string will be separated by a period
# This can be used to output clearly formatted things such as URLs and paths (a little bit formatted)
>>> print("www","python","org",sep=".")
www.python.org

The complete arguments of print() function are as follows:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The meaning of arguments:

#!/usr/bin/env python3

import time

print("--- Loading ---")

print("Loading",end = "")
for i in range(20):
    # Change the False to True, you will know how flush work
    print(".",end = '',flush = False)
    time.sleep(0.5)

Formatted output

We have talked about setting the delimiter mentioned previously in print(), it may be called as a formatted output. Except it, there are several ways to format the output.

Formatted String Literals

Formatted String Literals, aka f-strings. Use f or F before the opening single or triple quote, and you can write Python expressions in a string between a pair of curly braces to reference variables or literal values.

Here are some offical samples:

Simple reference variables:

>>> year = 2016
>>> event = 'Referendum'
>>> f'Results of the {year} {event}'
'Results of the 2016 Referendum'

Controls the digits of precision, here we set 3 decimal digits:

>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.

Setting an integer after : will set the minimum digits of the number, which can align column.

>>> for name, phone in table.items():
...     print(f'{name:10} ==> {phone:10d}')
... 
Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678

str.format()

This method like print(), but put the referenced arguments ​in .format(), as follows:

>>> yes_votes = 42_572_654
>>> no_votes = 43_132_495
>>> percentage = yes_votes / (yes_votes + no_votes)
# The content of single quotes is the `str` of `print()`, and the following `.format()` brackets are the corresponding arguments.
>>> '{:-9} YES votes  {:2.2%}'.format(yes_votes, percentage)
' 42572654 YES votes  49.67%'

Here is for number:

>>> print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"

This is default, and you also can use the symbol corresponding to the argument to reference it. The first string in the brackets corresponds to the number 0, and so on. As follows:

>>> print('{0} and {1}'.format('spam', 'eggs'))
spam and eggs
>>> print('{1} and {0}'.format('spam', 'eggs'))
eggs and spam

You can also use keyword arguments to reference the value by the name of the arguments, as follows:

>>> print('This {food} is {adjective}.'.format(
...       food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.

Combine them:

>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',other='Georg'))
The story of Bill, Manfred, and Georg.

You also can access variables value from a table by referencing the index or the name. Enclose the variable name with square brackets []. As follows:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
# Enclose the variable name with square brackets `[]`
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

It is not convenient to write a 0 with the square brackets [], so you can use two asterisks ** to simplify it. As follows:

>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678

More details: https://docs.python.org/3.8/library/string.html#formatstrings

Offical documents: https://docs.python.org/3.8/tutorial/inputoutput.html

I hope these will help someone in need~