[英]to allow the user to input a 3-digit number, and then output the individual digits in the number
how would i allow a user to input a 3-digit number, and then output the individual digits in the number in python 我将如何允许用户输入3位数字,然后在python中输出该数字中的各个数字
eg If the user enters 465, the output should be “The digits are 4 6 5” 例如,如果用户输入465,则输出应为“数字为4 6 5”
sorry if this sounds basic 抱歉,如果这听起来很简单
You use for your number num
: 您使用数字
num
:
num % 10
to extract the last digit. num % 10
提取最后一位。
num = num // 10
to remove the final digit (this exploits floored division). num = num // 10
以删除最后一位(这利用了累加除法)。
Finally, you want to get out the leading digit first. 最后,您想首先找出前导数字。 Therefore you adopt a recursive function to perform the above (which calls itself prior to printing the digit).
因此,您采用递归函数来执行上述操作(在打印数字之前先调用自身)。
The solution using str.isdigit
and re.sub
functions: 使用
str.isdigit
和re.sub
函数的解决方案:
import re
num = input('Enter number:')
if num.isdigit():
num_sequense = re.sub(r'(\d)(?=\d)', r'\1 ', num)
print("The digits are:", num_sequense)
else:
print("There should be only digits", num)
The output for the input 123
: 输入
123
的输出:
The digits are: 1 2 3
The output for the input a1s2d3
: 输入
a1s2d3
的输出:
There should be only digits a1s2d3
Hard to make in one line, anyway this should do exactly what you want: 很难在一行中制作,无论如何这应该可以完全满足您的要求:
inp = list(input())
print("The digits are ", end ='')
for i in inp:
print(i, end=' ')
If you don't care for formatting, one-liner is possible: 如果您不关心格式,则可以使用单行格式:
print("The digits are ",list(input()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.