如何检查输入是否为文本

时间:2014-12-10 21:34:57

标签: python string input

大家好我对python编码很陌生,但最近偶然发现了一个问题,在向人们询问名称时程序是否允许数字时,是否有一种简单的方法可以解决这个问题。

我的代码是这样的:

print("what is your name?")

name=input()

print("thank you",name,".")

我不完全确定这是确切的代码,但它确实做了这三件事。谢谢你,对不起它有点基础。我也想使用3.3.2。

2 个答案:

答案 0 :(得分:5)

您可以使用str.isalpha来测试字符串是否都是字母字符(字母):

>>> 'abcde'.isalpha()
True
>>> 'abcde1'.isalpha()
False
>>>

如果您有要测试的特定字符集,则可以使用allgenerator expression

chars = set('abcde')  # Put the characters you want to test for in here
all(c in chars for c in name)

此外,我使用了一组而不是常规字符串来提高效率。集合与O(1)具有in(常量)复杂度,其中字符串具有O(n)(线性)复杂度。换句话说,在集合中查找事物比在字符串中查找更快。


最后,您可以使用string.ascii_letters而不是输入整个字母:

>>> from string import ascii_letters
>>> ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>>

如果您想测试字母表中的所有字母加上另一个字符(例如连字符),这将变得特别有用:

chars = set(ascii_letters + '-')

答案 1 :(得分:0)

有几种方法可以解决这个问题。一个是做

之类的事情
if name.isalpha():
  # it's alphabetic
else:
  # it's not - prompt for new input

但是这会拒绝你可能喜欢的一些名字,比如“John Smith”或“Kate O'Conner”。

更谨慎的方法是

if any(map (lambda c: c.isdigit(), name)):
  # there's a digit in there, reject it
else:
  # it's got no digits, but maybe it still has punctuation that you don't want?
  # do further checks as needed

您还可以构建白名单:

import string
allowed_chars = string.ascii_letters+"'"+ "-" + " "  
   # allow letters, single-quote, hyphen and space
if all([c in allowed_chars for c in name]):
  # passes the whitelist, allow it
相关问题