【问题标题】:isolating grouped digits from integer input从整数输入中分离分组数字
【发布时间】:2021-01-25 12:47:28
【问题描述】:

我的目标是能够在终端中输入一个大(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)

我不确定如何调整它以使其正常工作。

【问题讨论】:

  • 你了解十进制数字系统的工作原理吗?为什么将输入值乘以 0?
  • 给定的解决方案不起作用吗?

标签: python python-3.x input integer


【解决方案1】:

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

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

【讨论】:

  • 如果它解决了您的目的,请考虑将其投票/标记为已接受的答案
【解决方案2】:

要求输入,直到它长 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:])

Asking the user for input until they give a valid responseUnderstanding slice notation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 2021-01-18
    • 2023-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多