繁体   English   中英

python:给定一个数字,如何打印列表中的字母表?

[英]python: How can I print an alphabet from a list, given a number?

给定一个从 1 到 26 的数字,我试图从列表中返回相应的 position 中的字母表。

例子:

Input = 1
Output = 'a'

我尝试了以下方法:

user_input = int(input("Enter a number from 1 to 26 "))

for item in aplhabet:
    print(aplhabet.index(item[aplhabet]))

正如预期的那样返回类型错误,因为我的列表中没有 integer 值。

我该怎么做才能从我的列表中返回一个元素,其中它的 position 等于用户输入的数字?

您可以使用索引:

alphabets = 'abcdefghijklmnopqrstuvwxyz'

user_input = int(input("Enter a number from 1 to 26: "))
print(alphabets[user_input - 1])

请注意,您需要减去 1,因为 Python 使用从 0 开始的索引。

您可以通过索引对列表进行索引:

import string
alphabet = list(string.ascii_lowercase)

user_input = int(input("Enter a number from 1 to 26 "))

if 0 < user_input <= 26:
    print(alphabet[user_input - 1])
else:
    print("please input a number between 1 and 26")

使用从 integer 到字符的 ASCII 转换,您可以执行以下操作,

n = int(input("Enter the number: "))
if(n > 0 and n < 27):
    print(chr(n + 96))
else: 
    print("Invalid input")

有3个答案。 他们都在完美地工作。 答案已经以 ASCII 值和字符串形式给出。 你可以用另一种方式来做。 创建一个数字键字典,并将其对应的字母作为值。 接受输入。 打印字典中存在的输入值。 你的代码:

d={1:"a",2:"b",3:"c",4:"d",5:"e",6:"f",7:"g",8:"h",9:"i",10:"j",11:"k",12:"l",13:"m",14:"n",15:"o",16:"p",17:"q",18:"r",19:"s",20:"t",21:"u",22:"v",23:"w",24:"x",25:"y",26:"z"}
x=int(input("Enter a number between 1 and 26= "))
print(d[x])

List1=['a','b','c','d','e','f','g','h','i','j','k','l' ,'m','n','o','p','q','r','s','t','u','v','w','x','你','z']

inputnumber = int(input("Enter Number")) for i, number in enumerate(range(len(List1)),start=1):

if i == inputnumber:
        print(List1[i])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM