我正在尝试编写一些允许用户输入单词的代码,但单词中的所有字母都必须是大写字母。该消息也不能包含空格或标点符号。
答案 0 :(得分:0)
简单的尝试可能是(对于单个单词而不是数字混合) -
inp = raw_input("F:")
if inp == inp.upper():
print "Hi"
else:
print "please enter Upper case word"
答案 1 :(得分:0)
Python字符串支持.isupper()
和.isalpha()
所以:
>>> def upperalpha(s):
... return s.isupper() and s.isalpha()
...
>>> upperalpha('ABC')
True
>>> upperalpha('ABc')
False
>>> upperalpha('ABC1')
False
>>> upperalpha('ABC DEF')
False
>>> upperalpha('ABCDEF')
True
>>> upperalpha('ABCDEF!')
False
一个简单的输入循环可能是:
>>> while True:
... word = input('Enter a word: ')
... if word.isupper() and word.isalpha():
... break
... else:
... print('Please enter only uppercase letters, no spaces or punctuation.')
...
Enter a word: asdf
Please enter only uppercase letters, no spaces or punctuation.
Enter a word: asdf123
Please enter only uppercase letters, no spaces or punctuation.
Enter a word: 123
Please enter only uppercase letters, no spaces or punctuation.
Enter a word: ABC123
Please enter only uppercase letters, no spaces or punctuation.
Enter a word: ABC 123
Please enter only uppercase letters, no spaces or punctuation.
Enter a word: ABC DEF
Please enter only uppercase letters, no spaces or punctuation.
Enter a word: ABC
>>>