有時候需要用int()函數轉換字符串為整型,但是切記int()只能轉化由純數字組成的字符串,如下例:
1 Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32 2 Type "copyright", "credits" or "license()" for more information. 3 >>> str1='214567' 4 >>> str2='' 5 >>> str3='fsdf214356' 6 >>> int(str1) 7 214567 8 >>> int(str2) 9 Traceback (most recent call last): 10 File "<pyshell#4>", line 1, in <module> 11 int(str2) 12 ValueError: invalid literal for int() with base 10: ''#不可轉換空字符串為整型 13 >>> int(str3) 14 Traceback (most recent call last): 15 File "<pyshell#5>", line 1, in <module> 16 int(str3) 17 ValueError: invalid literal for int() with base 10: 'fsdf214356'#不可轉換非純數字組成的字符串
18 >>>
非純數字組成的字符串強轉為整型會報錯:ValueError: invalid literal for int() with base 10