Python中如何拆分多位数字,分别提取百位、十位与个位数值
三位数数位拆分实现方法
基于你原有的取模、整除逻辑,对高位结果做二次运算即可提取对应数位:
num = 321 # 个位:直接对10取模 ones = num % 10 # 十位:先整除10移除个位,再对10取模得到十位数字 tens = (num // 10) % 10 # 百位:直接整除100移除后两位,得到百位数字 hundreds = num // 100 print(ones) # 输出 1 print(tens) # 输出 2 print(hundreds) # 输出 3
通用多位数数位拆分方案
如果需要适配任意位数的数字,可以选择以下两种实现方式:
- 字符串转换法:写法简单易读,适合不需要严格做数值运算的场景
num = 321 # 转字符串遍历后逐个转回整数,得到从高位到低位的数位列表 digits = [int(n) for n in str(num)] hundreds, tens, ones = digits print(hundreds, tens, ones) # 输出 3 2 1
- 纯数学运算提取:适合需要从低位到高位批量处理的场景
num = 321 digits = [] temp = num while temp > 0: digits.append(temp % 10) temp = temp // 10 # 反转列表得到从高位到低位的数位 digits = digits[::-1] hundreds, tens, ones = digits print(hundreds, tens, ones) # 输出 3 2 1
内容的提问来源于stack exchange,提问作者Hadeer Essam
相关产品推荐
相关产品推荐

