**python的格式化方式有下面三种:
- f with {expression}
- str.format()
- print-style format**
下面将通过代码的形式进行展示:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# https://docs.python.org/3.6/tutorial/inputoutput.html#input-and-output
def str_and_repr():
s = 'Hello world'
print(str(s)) # Hello world
print(repr(s)) # 'Hello world'
print(str(1/7))
print(repr(1/7))
# f with {expression}
def formatted_string_literals():
import math
# 3.142
print(f'The value of pi is approximately {math.pi:.3f}')
animals = 'eels'
# My hovecraft is full of eels.
print(f'My hovecraft is full of {animals}.')
# My hovecraft is full of 'eels'. !r applies repr()
print(f'My hovecraft is full of {animals!r}.')
# str.format
def str_format():
# We are the knights who say "Ni!"
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
# spam and eggs
print('{0} and {1}'.format('spam', 'eggs'))
# eggs and spam
print('{1} and {0}'.format('spam', 'eggs'))
# This spam is absolutely horrible.
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
# 下面两种方式都是一样的效果
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
print('Sjoerd: {0[Sjoerd]:d}, Jack: {0[Jack]:d}, Dcab: {0[Dcab]:d}'.format(table))
print('Sjoerd: {Sjoerd:d}, Jack: {Jack:d}, Dcab: {Dcab:d}'.format(**table))
# print-style format
# https://docs.python.org/3.6/library/stdtypes.html#old-string-formatting
def print_format():
import math
# The vale of pi is approximately 3.142.
print('The vale of pi is approximately %.3f.' %math.pi)
if __name__ == '__main__':
# str_and_repr()
# formatted_string_literals()
# str_format()
print_format()