【问题标题】:How to check if input is text [duplicate]如何检查输入是否为文本[重复]
【发布时间】:2014-12-10 21:34:57
【问题描述】:

大家好,我是 python 编码的新手,但最近偶然发现了一个问题,当向人们询问程序将允许数字的名称时,有没有简单的方法来解决这个问题。

我的代码是这样的:

print("what is your name?")

name=input()

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

我不完全确定这是确切的代码,但它可以完成这三件事。谢谢,对不起,这有点基本。我认为我也在使用 3.3.2。

【问题讨论】:

  • 检查输入的类型
  • 定义text。是只有no numbers,还是还有更多?

标签: python string input


【解决方案1】:

您可以使用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 + '-')

【讨论】:

  • 第二个可能会更好,因为 isalpha 不适用于连字符
  • 好点。我已经编辑了我的答案来处理连字符。
  • @iCodez :除了由于字符串具有固定且已知的大小之外,对于name 字符串,实际搜索复杂度为 O(1)。
  • 如果 OP 只想检查数字 if not any(x.isdigit() for x in s) 并允许所有其他字符
  • @iCodez 不,考虑到我们所描述的情况,我认为您不会。这个等式中最慢的元素是用户,没有很多方法可以让时间成为问题。
【解决方案2】:

有几种方法可以解决这个问题。一种是做类似的事情

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-16
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 2014-11-29
    相关资源
    最近更新 更多