String formatting symbols meaning
symbol | illustrate |
%c | Formatting characters and their ASCII codes [>>> '%c' %97 'a'] |
%s | format string |
%d | format integer |
%O | format unsigned octal number |
%x | format unsigned hexadecimal number |
%X | format unsigned hexadecimal number (uppercase) |
%f | Format a fixed-point number, specifying the precision after the decimal point |
%e | Format fixed-point numbers in scientific notation |
%E | Same as %e, format fixed-point numbers in scientific notation |
%g | Decide to use %f or %e according to the size of the value |
%G | The function is the same as %g, depending on the size of the value to use %f or %E |
Formatting operator helper
String escape character meaning
symbol | illustrate |
m.n | m is the minimum total width displayed and n is the number of digits after the decimal point |
- | for left alignment |
+ | Display a plus sign (+) in front of positive numbers |
# | Display '0o' in front of octal numbers and '0x' or '0X' in front of hexadecimal numbers |
0 | The displayed number is filled with '0' in front of the space instead of the space |
String escape character meaning
symbol | illustrate |
\' | apostrophe |
\" | Double quotes |
\a | system beeps |
\b | backspace character |
\n | newline |
\t | Horizontal Tab (TAB) |
\v | vertical tab |
\r | carriage return |
\f | form feed |
\O | characters represented by octal numbers |
\x | character represented by hexadecimal number |
\0 | represents a null character |
\\ | backslash |
0. What will the following line of code print?
"{{1}}".format( "do not print", "print")
'{1}'
1. In the following code, what parameters are a, b, c?
>>> "{a} love {b}.{c}".format(a="I", b="FishC", c="com")
'I love FishC.com'
keyword arguments
2. In the following code, what parameters are {0}, {1}, {2}?
>>> "{0} love {1}.{2}".format("I", "FishC", "com")
'I love FishC.com'
positional parameters
3. If you want to display Pi = 3.14, how should the string in front of format be filled in?
''.format('Pi = ', 3.1415)
'{0}{1:.2f}'
Move your hands:
0. Write a binary conversion program, the program is demonstrated as follows (hint, you can use bin() BIF for decimal conversion binary):
num = input("Please enter an integer (input Q to end the program):")
while num != 'Q':
if num.isdigit():
num = int(num)
print('Decimal -> Hexadecimal: %d -> %#x'%(num,num))
print('decimal -> hex: %d -> %#o'%(num,num))
print('decimal -> hex System: %d -> '%num,bin(num))
num = input("Please input an integer (input Q to end the program): ")
else:
if num == 'Q':
break
else:
num = input( "The input is illegal, please enter an integer (input Q to end the program):")
Note: If there is no num=input statement in if, it will prompt int and str type problems