如何操作列表中的字符串?

xpcnnkqh  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(338)

我一直在努力学习如何操作列表。例如,我已经成功地完成了一个简单的程序,要求用户输入一个数字并返回相应的月份。下面是我的解决方案的示例:

months = ['January', 'February',
          'March', 'April', 'May',
          'June', 'July', 'August',
          'September', 'October', 'November', 'December']

n = int(input("Enter a value between 1 and 12: "))

# Process & Output:

if 1 <= n <= 12:
    print ("The month is", months[n-1])
else:
    print ("Value is out of the range")

我现在的问题是,我该如何要求用户从列表中选择,而不是通过输入字符串来选择 int 价值
例子:

subjects= ['Maths','English','Science','History','Business']
n = (input("What is your favourite subject this semester? "))

我无法使用上述方法,因为它需要 int 价值

drkbr07n

drkbr07n1#

如果您想对照列表检查字符串输入,只需使用 in :

subjects = ['Maths','English','Science','History','Business']

subj_in = input("What is your favourite subject this semester? ")

if subj_in in subjects:

    print('Your favorite subject is ', subj_in)

else:

    print('Oh, they offer a course for that?')
pvcm50d1

pvcm50d12#

干得好:

subjects= ['Maths','English','Science','History','Business']

n = (input("What is your favourite subject this semester? "))

if n in subjects:
    print('great')
else:
    print('even better')
ttygqcqt

ttygqcqt3#

您已向用户询问该主题。现在你必须在主题列表中找到它。要做到这一点,就用这个

if n in subjects: 
    print ("valid subject")
else:
    print("invalid subject")

相关问题