用户输入字母后,我需要打印前一个字母,输入的字母和下一个字母

时间:2019-06-23 18:14:47

标签: python python-3.x

正如标题所述,我需要按字母顺序打印输入字母之前的字母,输入字母以及输入字母之后的字母。

对于尝试#1,我得到输入字母仅为B到Y并打印该字母的结果。

对于尝试#2,我按顺序获得字母B到Y的字母,但没有得到特定的字母。 (我在另一个帖子上发现了它,所以我对其工作方式感到困惑。)

对于尝试#3,我尝试了一个数组,但是我不确定如何利用该数组。

尝试1

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)

尝试2

letter = input("Enter a letter between B-Y ")

for c in range(1, 25):
    print(chr(ord('A')+c), end='')

尝试3

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])

2 个答案:

答案 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])