【问题标题】:Python exclude special characters and numbersPython 排除特殊字符和数字
【发布时间】:2018-09-09 17:32:55
【问题描述】:

有没有更好的方法来做到这一点?

我希望代码检测数字和特殊字符并打印:

“不允许数字”/“不允许特殊字符”

while True:
try:
    x = input('Enter an alphabet:')
except ValueError:
    print('sorry i do not understand that')
    continue
if x in ('1', '2','3','4','5','6','7','8','9','0'):
    print('Numbers not allowed')
    continue
else:
    break
if x in ('a', 'e', 'i', 'o', 'u'):
print ('{} is a vowel'.format(x))

elif x in ('A', 'E', 'I', 'O', 'U'):
print ('{} is a vowel in CAPS'.fotmat(x))
else:
print('{} is a consonant'.format(x))

【问题讨论】:

  • 第一次尝试-except 似乎毫无意义...您到底要验证什么?只有字母和空格?
  • 您可以import string 并检查是否x in string.ascii_letters 和数字检查是否x in string.digits

标签: python python-3.x


【解决方案1】:

一种方法是使用string 库。

这是一些伪代码,它假设输入一次是一个字符:

import string
x = input('Enter an alphabet:')
if x in string.digits:
    print('Numbers not allowed')
elif x not in string.ascii_letters:
    print('Not a letter')

string.ascii_letters是一个包含所有大小写字母的字符串:

print(string.ascii_letters)
#'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

同样,string.digits 是一个包含所有数字的字符串:

print(string.digits)
#'0123456789'

【讨论】:

  • 这是最好的解决方案。但作为替代方案,您始终可以手动 raise ValurError 而不是仅使用 print
【解决方案2】:

你可以通过几种方式做到这一点,但在我看来,pythonic 方法是这样的:

if any(char in string.punctuation for char in x) or any(char.isdigit() for char in x):
    print("nope")

【讨论】:

  • 为什么要打电话给setstring.punctuation 已经只包含唯一值。
  • 因为如果你想允许特定的字符,你可以很容易地添加类似 .replace() 的东西。
  • 我没有遵循你的逻辑。在这种情况下,any(char in set(string.punctuation) for char in x)any(char in string.punctuation for char in x) 产生相同的输出。在什么情况下会有所不同?
  • 你说得对,我当时在想别的东西。我不应该从节点项目切换到 python 问题。
【解决方案3】:

可能是这段代码完成了这项工作。

while True:
x = ord(input('Enter an alphabet:')[0])
if x in range(ord('0'), ord('9')):
    print('Numbers not allowed')
    continue
if x not in range(ord('A'), ord('z')):
    print('Symbols not allowed')
    continue
if chr(x) in 'aeiou':
    print('{} is a vowel'.format(chr(x)))
elif chr(x) in 'AEIOU':
    print('{} is a vowel in CAPS'.format(chr(x)))
else:
    print('{} is a consonant'.format(chr(x)))
continue

我们选择数字,取消选择除字母以外的任何字符,然后完成这项工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    相关资源
    最近更新 更多