【问题标题】:validation from input if character is alphabetical [duplicate]如果字符是字母顺序,则从输入验证[重复]
【发布时间】:2016-08-25 20:21:14
【问题描述】:

您好,我是编程新手,我正在尝试编写一个代码,该代码将从输入中收集信息并确定它是否是有效的字母表。

我之前曾问过这个问题,但给出的答案没有用,所以我再次问这个问题。请帮忙

words = []
word = input('Character: ')
while word:
 if word not in words:
  words.append(word)
 word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')

假设我选择三个字母然后输出我的代码然后按下回车 第四天, 代码将是:

Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.

我想添加到这段代码中,这样当我输入的字符不是 从字母表来看,代码会做这样的事情。

Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.

这正是我想要的输出。

【问题讨论】:

  • 我已经展示了我尝试过的内容
  • 添加了对上一个问题的答案。这个应该被标记为重复。

标签: python


【解决方案1】:

如果你看一下字符串类,我想你会发现它有一些你会发现有用的变量。

from string import letters
word = raw_input("Character: ")
words = []
while word and word in letters:
  if word not in words:
    words.append(word)
  word = raw_input('Character: ')

我在这台计算机上没有 python,但我认为你会发现这段代码有效。此外,字符串类还有其他一些您可能会觉得有用的变量,包括数字、标点符号、可打印等

【讨论】:

  • 我会把它放在我的代码中的什么地方
  • 伙计,这几乎完全符合您的代码。你应该能够弄清楚把它放在哪里。我想我遗漏了打印声明。就是这样。
  • 您的问题是如何验证字符是字母,而不是如何为您编写整个问题。我已经回答了你的问题。你应该可以从这里弄清楚。
  • 代码不起作用。您不能导入姓名字母
  • 也许您应该发布您正在使用的 python 版本。它对我来说很好用。
【解决方案2】:

您可以使用string.isalpha() 函数来查找输入是否为字母。

>>> 'a'.isalpha()
True       <-- as 'a' is alphabet
>>> 'A'.isalpha()
True       <-- as 'A' is also alphabet
>>> ''.isalpha()
False      <-- empty string
>>> '1'.isalpha()
False      <-- number
-------------------------
>>> 'ab'.isalpha()
True       <-- False, since 'ab' is alphabetic string

# NOTE: If you want to restrict user to enter only one char at time,
# you may add additional condition to check len(my_input) == 1
>>> len('ab') == 1 and 'ab'.isalpha()
False

为了得到用户的输入,你可以这样做:

  • 使用raw_input

    x = raw_input() # Value of x will always be string

  • 使用input

    x = input() # Value depends on the type of value

    x = str(x) if x else None # Convert to str type. In case of enter with value set as None

【讨论】:

  • 我试过isalpha,你必须输入为字符串
  • raw_input() 以字符串形式返回所有内容
  • 我的程序说错误原始输入未定义
  • 不是raw-input instead raw_input. Note the _`
  • 我知道。它仍然说
猜你喜欢
  • 1970-01-01
  • 2020-11-18
  • 2016-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多