Python - Validation to ensure input only contains characters A-Z - python

I'm creating a program in Python 3.x where it asks the user for their first name and then last name and stores these in variables which are then concatenated into one variable:
firstName = input("What's your first name? ")
lastName = input("What's your first name? ")
name = firstName + " " + lastName
I tried:
while True:
try:
firstName = input("What's your first name? ")
lastName = input("What's your first name? ")
name = firstName + " " + lastName
break
except ValueError:
print("That's invalid, please try again.")
which ensures that a string is inputted, but inputting 'bob38', '74' or '][;p/' all count as string values, so these would be accepted, which is not what I want to happen.
I want valid input to only contain the letters A-Z/a-z (both uppercase and lowercase), and if the input contains anything else, an error message is outputted (e.g. 'That's invalid, try again.') and the user is asked the question again. How would I do this?

What you want to do is actually check if your string is not isalpha() and output an error and continue your loop until you get a valid entry.
So, to give you an idea, here is a simple example:
while True:
name = input("input name")
if name.isalpha():
break
print("Please enter characters A-Z only")
print(name)
Note, that as mentioned in the comments to this question, this is limited to only names that contain letters. There are several valid names that will contain ' and - that should probably be considered when wanting to validate names.

There is another solution. It's not as efficient as using re or isalpha but allows you to easily customize the characters you allow:
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
# Just insert other characters into that string if you want to accept anything else.
while True:
firstName = input("What's your first name? ")
if all(char in valid_characters for char in firstName):
break
print("That's invalid, please try again.")
The all checks if all characters from firstName are contained in the valid_characters string and returns False if any of them is not in it.
So to add whitespace and minus - you can alter it slightly:
valid_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ -'
# whitespace is here ------------------------------^

assert all('a'<=letter<='z' or 'A'<= letter <= 'Z' for letter in name)
This will throw an error if name contains a non alphabet letter.

You can use a simple regular expression for this -
import re
is_valid_name = r'[a-zA-Z]+'
if bool(re.match(firstName, is_valid_name)) and bool(re.match(lastName, is_valid_name)):
name = firstName + lastName
else:
print('thats invalid')

Related

How do I make an input() detect if the user input is something other than a string?

I am fairly new to Python and I wanted to generate a simple user input that asks for your name. I got the prompt to work but when I added code that detects if the input is not a string, it doesn't let me input anything at all.
It was working up until I added the code that tells the user if they used an unsupported character.
Here's the code I have so far:
while True:
name = input('What is your name? ')
if name is str:
print('Hi,%s. ' % name)
if name != str:
print('That is not a valid character!')
Python supplies methods to check if a string contains on alphabets, alphanumeric or numeric.
isalpha() returns True for strings with only alphabets.
isalnum() returns True for strings with only alphabets and numbers and nothing else.
isdigit() returns True for strings with only numbers.
Also your if-else statement is off
name = input('What is your name? ')
if name.isalpha():
print('Hi,%s. ' % name)
else:
print('That is not a valid character!')
When you do
name = input('What is your name? ')
you get a string called name, so checking it it is a string won't work.
What you can check is if it's an alphabetical character, using isalpha:
if name.isalpha():
# as you were
There are various other string methods ( see here ) which start is to check for numbers, lower case, spaces and so on.

Validating existence of symbols in input

So I want to validate the input of a first name by checking if it has invalid characters. It works for blank entries and numbers but won't pick up any of the symbols.
import re
while True:
f_name = input('First name: ').strip().lower()
if f_name == '':
print("* you haven't entered anything.")
continue
elif re.search('[0-9]', f_name):
print("* entry can't contain numbers. please try again with only letters.")
continue
elif re.search('[~!##£€$¢¥§%^&*/()\\-_+={}[]:;"\'<>,.?]', f_name):
print("* entry can't contain symbols. please try again with only letters.")
continue
else:
break
It works when only a few symbols are in the brackets but I need to check a wide range, is there any way to fix this?
I believe you can use [^\w/]|_.
[^\w/] matches alphanumeric + _ as well as /
|_ excludes underscore since _ is included by default with alphanumeric characters with [^\w/]:
import re
while True:
f_name = input('First name: ').strip().lower()
if f_name == '':
print("* you haven't entered anything.")
continue
elif re.search('[0-9]', f_name):
print("* entry can't contain numbers. please try again with only letters.")
continue
elif re.search('[^\w-]|_', f_name):
print("* entry can't contain symbols. please try again with only letters.")
continue
else:
break
Check for any of characters not being alphanumeric like:
any(not c.isalnum() for c in mystring)
This link may also help further: How to check if a string has ANY special characters?
'[~!##£€$¢¥§%^&*/()\\-_+={}[]:;"\'<>,.?]'
is not a valid regex. Well, at least not the regex that you're looking for. You have some unescaped characters in there, such as ] and " that messes it up. You can put it into a regex tester to see what I mean.
Doing it with a regex isn't the best option anyways. You have plenty of options for doing this, depending on your desired behavior. As others have mentioned, you could use isalnum() and isalpha() to check if a string only contains alphanumeric or alphabetical characters.
If you only want to exclude a special list of symbols and not other special symbols, you can use the intersection of two sets:
DISALLOW_SYMBOLS = set("~!##£€$¢¥§%^&*/()\\-_+={}[]:;\"'<>,.?")
f_name = input('First name: ').strip().lower()
name_set = set(f_name)
symbols = DISALLOW_SYMBOLS.intersection(name_set)
if symbols:
print("* entry contains these symbols that are not allowed: ", symbols)

How to require a capital letter and a number for an input string in python?

password = input(str("Please enter a password with a capital letter and a number: "))
for char in password:
if password.islower() and "1234567890" not in password:
print("Your password will need to have at least one number and at least one capitalized letter")
password = input("Please enter another password: ")
**The error phrase will print if a password is entered without a number or capital, but if a capital is used in the input the error string doesn't run even though the input is still missing a number. Same for if the input has a number but not a capital letter. I want both a capital letter and a number to be required for the input as you can probably tell. Thanks.
edit:
I don't want to know how to make a password requirement program. I specifically want to know why the "and not" is not working.**
I just happened to write this yesterday.
Season to taste :-)
import re
import getpass
while True:
pwd = getpass.getpass('please enter a password: ')
if len(pwd) >= 8 and re.search('[0-9]', pwd) and re.search('[A-Z]', pwd):
if pwd != getpass.getpass('please reenter password: '):
print('passwords do not match')
else:
break
else:
print('passwords must contain 8 characters and at least one uppercase letter and one digit')
print('approved pwd:', pwd)
I specifically want to know why the "and not" is not working.
"1234567890" not in password
is negation of "1234567890" in password which for password being str is checking if "1234567890" is substring of password.
Consider that:
print("123" in "123123123") # True
print("123" in "1") # False
print("123" in "321") # False
To check if any character from one str is present in second str you might check if intersection is not empty - just turn second str into set, get interesection with first, and use bool function on result, thus getting True if at least one of characters of first str is present in second and False otherwise:
x = "1234567890"
y = "sometextandnumber0"
print(bool(set(y).intersection(x))) # True

Prevent input() from being anything but alphabet characters

I am attempting to make a program for the sake of self-knowledge. I want to ask the user what their name is, and I only want the user to be able to use letters from the alphabet to answer, or only strings. I do not want them to be able to answer with numbers, symbols, etc.
def cc():
name = (input("""Hello, what happens to be your first name?
> """))
if type(name) is str:
print("You have entered a name correctly.")
elif type(name) is int:
print("Your name cannot be an integer. Try again.")
cc()
cc()
You can enforce this requirement using str.isalpha. From the documentation:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.
Here is an example program:
while True:
name = input('Enter a name using only alphabetic characters: ')
if name.isalpha():
break
Demo:
Enter name using only alphabetic characters: Bo2
Enter name using only alphabetic characters: Bo^&*(
Enter name using only alphabetic characters: Bob
Note this method will not work for people with hyphenated names such as "Anne-Marie".
I agree that this question is a little misleading. However, with what you have said, you just need to use a regex to accomplish this.
import re
...
if not re.findall('[^a-zA-Z]', 'abc1'):
print("You have entered a name correctly.")
else
print("Your name cannot be an integer. Try again.")
cc()

Python Encryption

So for an exam question I've followed this specific pseudo code which basically makes a program which encrypts a number sequence using the same principle as the ceasar cipher. It should work but for some reason it returns the error.
TypeError: 'int' object is not iterable
Heres the code, i hope you guys can help me, much appreciated
plainNum = input("enter a number to encode ")
codedNum = ' '
Key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Use raw_input if you expect a string:
plainNum = raw_input("enter a number to encode ")
input() interprets the input as if it is Python code; enter 5 and it'll return an integer, enter 'some text' (with quotes) and it'll return a string. raw_input() on the other hand returns the entered input uninterpreted.
Most dirty fix of all, simply change
for i in plainNum:
with
for i in str(plainNum):
This is working but not if I use a decimal and it doesn't behave if I enter words or spaces. Consider checking first that the entry is a number with something like:
try:
float(element)
except ValueError:
print "Not a float"
after stripping any whitespace with something like:
plainNum = plainNum.strip()
But this outputs the encoded digits of your entered integer:
plainNum = raw_input("enter a number to encode ")
codedNum = ' '
key = input("enter a key ")
for i in plainNum:
codedNum = codedNum + str((int(i)+key)%10)
print codedNum
Ask the user for the number with raw_input. This makes the input a string which you can iterate over with:
for char in plainNum:
Yes, this is a now a char in a string and so you've used the int(i) function.
you maybe also wanna change key to Key to reflect what variable is declared
and also make codeNum initially equal to '' instead of ' ' (no space vs space)
just book keeping stuff

Categories

Resources