python怎麼取各個數位的數?使用者34784916162519232019-12-28 21:05:42

a = 12345 取個位 : b = (a / 1) % 10 = a % 10 取十位: b = (a / 10) % 10 取百位: b = (a / 100) % 10 以此類推。假設輸入的數是n, n不為0 n=某數 while n>0。 (n,r) = divmod(n,10) print r 其中(n,r) = divmod(n,10) r是個位數。n是其它高位數,divmod包含 除和求餘數。。或者用 [int(i) for i in str(n)] str(n) 把數變成字串 int(i) 把字串裡的字母變成數字。