正如标题所述,我需要按字母顺序打印输入字母之前的字母,输入字母以及输入字母之后的字母。
对于尝试#1,我得到输入字母仅为B到Y并打印该字母的结果。
对于尝试#2,我按顺序获得字母B到Y的字母,但没有得到特定的字母。 (我在另一个帖子上发现了它,所以我对其工作方式感到困惑。)
对于尝试#3,我尝试了一个数组,但是我不确定如何利用该数组。
valid_letters = 'bcdefghijklmnopqrstuvwxyBCDEFGHIJKLMNOPQRSTUVWXY'
while True:
letter = input("Enter a letter between B-Y ")
if all(char in valid_letters for char in letter):
break
print(letter)
letter = input("Enter a letter between B-Y ")
for c in range(1, 25):
print(chr(ord('A')+c), end='')
valid_letters = ['B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y']
print(valid_letters[5])
答案 0 :(得分:0)
# include A and Z in the string so we can print them if the user enters B or Y
letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
# keep going until the user quits by entering "q"
while True:
letter = input("Enter a letter between B-Y, or q to quit ")
if letter == 'q':
print('Goodbye')
break
# if letter not in correct range, print a message and keep looping
if not 'B' <= letter <= 'Y':
print('Invalid input')
continue
# find the index position within letters of the entered letter
position = letters.index(letter)
# print previous, current, and next letters
print ('letter before: %s' % letters[position-1])
print ('entered letter: %s' % letter)
print ('letter after: %s' % letters[position+1])
答案 1 :(得分:0)
使用for循环尝试这种方式,
valid_letters = ['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']
letter = input("Enter letter betwen B and Y: ")
for i in range(len(valid_letters)):
if letter == valid_letters[i]:
print(valid_letters[i-1])
print(valid_letters[i])
print(valid_letters[i+1])