[英]python: How can I print an alphabet from a list, given a number?
Given a number from 1 to 26, I'm trying to return an alphabet in the corresponding position from a list.给定一个从 1 到 26 的数字,我试图从列表中返回相应的 position 中的字母表。
Example:例子:
Input = 1
Output = 'a'
I have tried the following:我尝试了以下方法:
user_input = int(input("Enter a number from 1 to 26 "))
for item in aplhabet:
print(aplhabet.index(item[aplhabet]))
As expected that returns a type error because there are no integer values in my list.正如预期的那样返回类型错误,因为我的列表中没有 integer 值。
What can I do to return an element from my list in which its position is equal to the users number input?我该怎么做才能从我的列表中返回一个元素,其中它的 position 等于用户输入的数字?
You can use indexing:您可以使用索引:
alphabets = 'abcdefghijklmnopqrstuvwxyz'
user_input = int(input("Enter a number from 1 to 26: "))
print(alphabets[user_input - 1])
Note that you need to subtract 1, since Python uses 0-based index.请注意,您需要减去 1,因为 Python 使用从 0 开始的索引。
You can index a list by its index:您可以通过索引对列表进行索引:
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")
Using ASCII conversion from integer to character, you can do it as follows,使用从 integer 到字符的 ASCII 转换,您可以执行以下操作,
n = int(input("Enter the number: "))
if(n > 0 and n < 27):
print(chr(n + 96))
else:
print("Invalid input")
There are 3 answers.有3个答案。 All of them are perfectly working.
他们都在完美地工作。 The answers are already given in ASCII values and string.
答案已经以 ASCII 值和字符串形式给出。 You can do it another way.
你可以用另一种方式来做。 Create a dictionary of number key and it's corresponding alphabet as value.
创建一个数字键字典,并将其对应的字母作为值。 Take the input.
接受输入。 Print the value of of the input present in the dictionary.
打印字典中存在的输入值。 Your code:
你的代码:
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','y','z'] 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): 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.