Python - Validation to ensure input only contains characters A-Z
我在python3.x中创建了一个程序,它要求用户输入名字,然后输入姓氏,并将其存储在变量中,然后将变量连接到一个变量中:
1 2 3 | firstName = input("What's your first name?") lastName = input("What's your first name?") name = firstName +"" + lastName |
我试过:
1 2 3 4 5 6 7 8 | while True: try: firstName = input("What's your first name?") lastName = input("What's your first name?") name = firstName +"" + lastName break except ValueError: print("That's invalid, please try again.") |
这样可以确保输入一个字符串,但输入"bob38"、"74"或"[;p/"都将计为字符串值,因此可以接受这些值,这不是我想要的结果。
我希望有效输入只包含字母a-z/a-z(大写和小写),如果输入包含任何其他内容,则会输出一条错误消息(例如,"这是无效的,请重试"),并再次询问用户问题。我该怎么做?
您要做的是实际检查字符串是否不是
所以,为了给你一个想法,这里有一个简单的例子:
1 2 3 4 5 6 7 | while True: name = input("input name") if name.isalpha(): break print("Please enter characters A-Z only") print(name) |
注意,正如本问题的注释中所述,这仅限于包含字母的名称。有几个有效的名称包含
还有另一个解决方案。它不如使用
1 2 3 4 5 6 7 8 | valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' # Just insert other characters into that string if you want to accept anything else. while True: firstName = input("What's your first name?") if all(char in valid_characters for char in firstName): break print("That's invalid, please try again.") |
因此,要添加空白
1 2 | valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -' # whitespace is here ------------------------------^ |
如果名称中包含非字母,则会引发错误。
您可以为此使用简单的正则表达式-
1 2 3 4 5 6 7 | import re is_valid_name = r'[a-zA-Z]+' if bool(re.match(firstName, is_valid_name)) and bool(re.match(lastName, is_valid_name)): name = firstName + lastName else: print('thats invalid') |