eg: >>> print('{} and {}'.format('hello','world')) # 默认左对齐 #hello and world >>> print('{:10s} and {:>10s}'.format('hello','world')) # 取10位左对齐,取10位右对齐 #hello and world >>> print('{:^10s} and {:^10s}'.format('hello','world')) # 取10位中间对齐 # hello and world >>> print('{} is {:.2f}'.format(1.123,1.123)) # 取2位小数 #1.123 is 1.12 >>> print('{0} is {0:>10.2f}'.format(1.123)) # 取2位小数,右对齐,取10位 #1.123 is 1.12
>>> c = 3-5j >>> ('The complex number {0} is formed from the real part {0.real} and the imaginary part {0.imag}.').format(c) 'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'
>>> x=[0,1] >>> 'The first element of {x} is {x[0]}'.format(x=x)
name = 'jack' age = 18 sex = 'man' job = "IT" salary = 9999.99
print(f'my name is {name.capitalize()}.') #my name is Jack. print(f'I am {age:*^10} years old.') #I am ****18**** years old. print(f'I am a {sex}') #I am a man print(f'My salary is {salary:10.3f}') #My salary is 9999.990 print(f'My salary is {salary*12} a year') #My salary is 119999.88 a year
f"""he introduces himself {"I'm Tom"}"""
使用%、format、f-string打印九九乘法表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
for i in range(1,10): for j in range(1,i+1): print("%s*%s=%s" % (j,i,j*i),end=" ") print("\n")
for i in range(1,10): for j in range(1,i+1): print("{0}*{1}={2}".format(j,i,j*i),end=" ") print("\n") for i in range(1,10): for j in range(1,i+1): print(f"{j}*{i}={j*i}",end=" ") print("\n")