format of python formatting function

Table of contents

1. %s

2. format

3. f 

4. Python conversion specifiers

5. Formatted output numbers

6. Add color



Python print string has the following implementation methods, one based on %s, one using format, and the f function can also be used.

1. %s

This is the easiest way, but you need to pay attention to the order.

string = "Hello %s %s"%("world",'!')
print(string) 
# Hello world !

2. format

There are two ways to pass parameters to format, one is in order and the other is in dictionary.

string = 'Hello {0} {1}'.format("World","!")
print (string)
# Hello World !

string = "Hello {name} {placeholder}".format(name='World',placeholder='!')
print (string)
# Hello World !


# 传递参数的方式
## list
parameters=["World","!"]
string = 'Hello {0} {1}'.format(*parameters)
print(string)
# Hello World !
## dict

parameters=dict(name='World',placeholder='!')
string = "Hello {name} {placeholder}".format(name='World',placeholder='!')
print(string)
# Hello World !

3. f 

f is a relatively new function that can support calculations in strings and print out.

a = 1 
b = 2 
string = f"a={a},b={b},a+b={a+b}"
print(string)
# a=1,b=2,a+b=3


string = f"a={a},b={b},a+b={a+b:.2f}"
print(string)
# a=1,b=2,a+b=3.00

4. Python conversion specifiers

conversion specifier explain
%d、%i Convert to signed decimal integer
%o Convert to signed octal integer
%x、%X Convert to signed hexadecimal integer
%e Convert to a floating point number expressed in scientific notation (e lowercase)
%E Convert to a floating point number represented by scientific notation (uppercase E)
%f、%F Convert to decimal floating point
%g Smart select to use %f or %e format
%G Smart select to use %F or %E format
%c Formatting characters and their ASCII codes
%r Use the repr() function to convert an expression to a string
%s Use the str() function to convert an expression to a string

5. Formatted output numbers

# 保留两位小数
number = "number: %.2f" % (0.23423)
# number = "number: {0:.2f}".format(0.23423)
# number = "number: {num:.2f}".format(num=0.23423)
print (number)
# number: 0.23
# 转换成百分数
number = "number: %.2f%%" % (0.23423*100)
# number = "number: {0:.2f}%".format(0.23423*100)
# number = "number: {num:.2f}%".format(num=0.23423*100)
print(number)
# number: 23.42%

6. Add color

from termcolor import colored
string = "red string"
print(colored(string,'red'))
# red string

Guess you like

Origin blog.csdn.net/lpfangle/article/details/125898983
Recommended