《Python核心编程》P21输入数值字符串→转整型
>>> num=input() 1234 >>> num '1234' >>> num=input(haha:) SyntaxError: invalid syntax >>> num=input('haha:') haha:23 >>> num '23' >>> print(num) 23 ' >>> print(num) 23 >>> print('123:sdf',num) 123:sdf 23 >>> print('123:sdf:',num) 123:sdf: 23 >>> print('123:sdf: ',num) 123:sdf: 23 >>> print('zhuanzhengxing',int(num)) zhuanzhengxing 23 >>> print(int(num)) 23 >>> print(int(num)*2) 46 >>> print('zhuanzhengxing',int(num)*2) zhuanzhengxing 46 >>> print('zhuanzhengxing%d',int(num)*2) zhuanzhengxing%d 46 >>> print('%d',int(num)*2) %d 46 >>> print(%d,int(num)*2) SyntaxError: invalid syntax >>> print(%d%int(num)*2) SyntaxError: invalid syntax >>> print('%d'%int(num)*2) 2323 >>> # #前有%d,后用的逗号,没用%:%d当做字符输出了 >>> print(%int(num)*2) SyntaxError: invalid syntax >>> print('zhuanzhengxing%d'%int(num)*2) zhuanzhengxing23zhuanzhengxing23 >>> print('zhuanzhengxing'%int(num)*2) SyntaxError: unexpected indent >>> print('zhuanzhengxing'%int(num)*2) Traceback (most recent call last): File "<pyshell#31>", line 1, in <module> print('zhuanzhengxing'%int(num)*2) TypeError: not all arguments converted during string formatting >>> #后面有% 没用逗号,而前面没有%,错误
原图:
>>> num=input('n:') n:1234 >>> print('sdf:',n) Traceback (most recent call last): File "<pyshell#72>", line 1, in <module> print('sdf:',n) NameError: name 'n' is not defined >>> print('sdf:',num) sdf: 1234 >>> print('sdf:',int(num)) sdf: 1234 >>> print('sdf:',int(num)*2) sdf: 2468 >>> print('sdf:%d',int(num)*2) #前有%d,后用的逗号,没用%:%d当做字符输出了 sdf:%d 2468 >>> print('sdf:%d'%int(num)*2) sdf:1234sdf:1234 >>> print('sdf:%d'%int((num)*2))) SyntaxError: invalid syntax >>> print('sdf:%d'%(int((num)*2))) sdf:12341234 >>> print('sdf:%d'%(int(num)*2)) sdf:2468 >>> >>> print('sdf:'%int(num)*2) #后面有% 没用逗号,而前面没有%,错误 Traceback (most recent call last): File "<pyshell#84>", line 1, in <module> print('sdf:'%int(num)*2) TypeError: not all arguments converted during string formatting >>> print('sdf:'%(int(num)*2)) Traceback (most recent call last): File "<pyshell#85>", line 1, in <module> print('sdf:'%(int(num)*2)) TypeError: not all arguments converted during string formatting >>>
#int(num)没括号不行
>>> print('sdf:%d'%int num*2) SyntaxError: invalid syntax >>> print('sdf:%d'%int num) SyntaxError: invalid syntax >>>
原图: #int(num)没括号不行; #字符串*2