[英]How do I check if a string with a user given input is equal to a certain letter/ word in Python
[英]How to print the letter of a certain string that the user wants
我是 python 的新手,有一个问题。 我想创建一个程序,要求用户输入 1 到 26 之间的数字。然后使用此响应打印字母表中的相应字母(a 是第一个字母,b 是第二个字母,z 是第 26 个字母,等等)。 如果出现 IndexError,请打印 ("Your number is out of range")。 对于所有其他错误,打印(“发生其他事情”)。
现在我有这个:
try:
theAlphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet=input("Give me a number between 1 and 26.")
print(len(theAlphabet)
except IndexError:
print("Your number is out of range")
except:
print("Something else occurred")
我不知道在print(len(theAlphabet)
部分之后该做什么。
print(chr(ord("a")+alphabet))
ord("a") 为您提供字母“a”的 ASCII 值。 然后你可以添加号码。 chr(x) 为您提供值的 ASCII 字符。 请注意,这不是检查范围内的错误,但最好以另一种方式进行。
您可以使用索引访问字符串,但您需要使用int()
将用户输入转换为整数,并将值减少 1。
try:
theAlphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet=input("Give me a number between 1 and 26: ")
print(len(theAlphabet))
print(theAlphabet[int(alphabet)-1])
except IndexError:
print("Your number is out of range")
except:
print("Something else occurred")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.