将分组数字与整数输入隔离开来



我的目标是能够将一个大的(6位数(数字输入到终端,并使其返回中间的两位数字,交换。

我的代码如下:

a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
addition = ((a * 0) + (b * 0) + (d * 10))
addition_two = ((c) + (e * 0) + (f * 0))
print(addition + addition_2)

我不确定如何调整它才能正常工作。

我不了解所有的复杂性。如果你只想要中间的两位数字(并且它们被交换(,你可以简单地使用:

n = input("Enter number: ")
ans = n[2:4]
return int(ans) //if you want int type, else ans would suffice as str

请求输入,直到其长度为6并且仅由数字组成。不需要将任何东西转换为数字,可以通过正确地对字符串进行切片来直接处理:

while True:
k = input("6 digit number")
if not all(c.isdigit() for c in k) or len(k) != 6:
print("Not a six digit number")
else:
break
# string slicing:
#   first 2 letters
#   reversed 4th and 3rd letter
#   remaining letters
print(k[:2] + k[3:1:-1] + k[4:])

请参阅询问用户输入,直到他们给出有效响应和理解切片符号

最新更新