【问题标题】:Python: Can you display a single int based off the index of an int a user inputedPython:您能否根据用户输入的 int 的索引显示单个 int
【发布时间】:2021-03-05 04:01:59
【问题描述】:

所以:

print('Enter a 4 digit number: ')
user = int(input())

假设用户输入 4325

是否可以在不使用列表的情况下获取单个数字(例如 2)并将其显示给用户?或者这样的事情需要一个列表或数组吗?

【问题讨论】:

  • 4325 // 100 % 10 == 3
  • 我看不出使用列表/元组有什么问题?

标签: python-3.x integer user-input


【解决方案1】:

在 Python 中,您可以像从列表中获取索引一样获取字符串中的字符。换句话说,您可以执行以下操作:

user = input('Enter a 4 digit number: ')
num = int(user[2])

这是什么意思?这意味着您将获得用户的输入,并将其存储在变量user 中。请注意,这是一个字符串。然后,您将获取索引 2 处的字符(第三个字符,而不是第二个),并将其更改为 int,并将其存储在变量 num 中。现在,您可以执行print(num),它应该显示整数2

另外,在 Python 中,您可以遍历字符串。要实现您的其他目标,您可以执行以下操作:

dict = {
    "0": "a",
    "1": "b",
    "2": "c",
    "3": "d",
    "4": "e",
    "5": "f",
    "6": "g",
    "7": "h",
    "8": "i",
    "9": "j"
}

user = input('Enter a number: ')
newstr = ''
for char in user:
    newstr += dict[char]
print(newstr)

假设用户再次输入4325。程序将遍历字符串,并将单个字符存储在字符串char 中。然后,它从字典dict 中获取值,并将其添加到newstr。然后,它将继续这个过程,直到它到达字符串的末尾,它会打印出newstr,这次它的值是edcf

【讨论】:

    【解决方案2】:

    在 Python 中,你可以作为用户输入一个字符串,然后拆分它的第二个索引并转换为整数类型。

    user = int(input('输入一个4位数字:')[2])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多