格式化输出
格式化输出
age=input('age :>>>')
print('my age is'+age)
age :>>> 22
my age is22
age=input('age :>>>')
print('my age is '+age)
age :>>> 22
my age is 22
age=input('age :>>>')
print('my age is',age)
age :>>> 22
my age is 22
name=input('name:>>>')
age=input('age :>>>')
print('my age is',age,',my name is',name)
name:>>> xy
age :>>> 12
my age is 12 ,my name is xy
占位符
name=input('name:>>>')
age=input('age :>>>')
print('my age is %s, my name is %s'%(age, name))
name:>>> xy
age :>>> 12
my age is 12, my name is xy
name=input('name:>>>')
age=input('age :>>>')
print('my age is %d, my name is %d'%(age, name))
name:>>> 1
age :>>> 1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[12], line 5
1 name=input('name:>>>')
3 age=input('age :>>>')
----> 5 print('my age is %d, my name is %d'%(age, name))
TypeError: %d format: a real number is required, not str
name=input('name:>>>')
name=int(name)
age=input('age :>>>')
age=int(age)
print('my age is %d, my name is %d'%(age, name))#%d强制int
name:>>> 1
age :>>> 1
my age is 1, my name is 1
f-string格式化
name=input('name:>>>')
age=input('age :>>>')
#print('my age is %d, my name is %d'%(age, name))
#print('my age is {}, my name is {}',format(age, name))#两个落后的方法
print(f'my age is {age},my name is {name}')
name:>>> XY
age :>>> 11
my age is 11,my name is XY
print(f'my age is {int(age)+1},my name is {name}')
my age is 12,my name is XY
用这个方法最简便。
print(f'my age is {int(age)+1},my name is{"xy"}')
my age is 12,my name isxy