简体   繁体   中英

Python exclude special characters and numbers

Is there a better way to do this?

I want the code to detect numbers and special characters and print:

"numbers not allowed" / "special characters not allowed"

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))

One way is to use the string library.

Here is some psuedocode, which assumes that the input is one character at a time:

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 is a string that contains all the uppercase and lowercase letters:

print(string.ascii_letters)
#'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Likewise, string.digits is a string that contains all of the digits:

print(string.digits)
#'0123456789'

You could do it a couple of ways but the pythonic method seems to me to be like so:

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

May be this code does the job.

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

We select numbers, deselect whatever character except letters and then does the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM