How to make input only accept a-z etc - python

I'm having trouble getting my input to accept only a-z and A-Z letters. This is what I came up with
while(not(studentName == "END")):
studentName = input("What is the name of the student (END to finish) ")
if not re.match("^[a-z]*$", studentName):
print("Only letters are allowed")
elif len(studentName) == 0:
print("Insufficient characters. Please try again.")
else:
studentsNames.append(studentname)
However I just come up with an error "re not defined".
What do I do :C

Instead of using regular expressions, I like to use the built-in string methods. One of these is str.isalpha(), which, when called on a string, returns True if the string contains only A-z. So instead of:
if not re.match("^[a-z]*$", studentName):
print("Only letters are allowed")
I'd just write:
if not studentName.isalpha():
print("Only letters are allowed!")

You need to import re module and you must need to change your regex as,
if not re.match(r"^[A-Za-z]+$", studentName):
Just type the below code at the top of your python script.
import re
Your regex "^[a-z]*$" would match zero or more lowercase letters. That is, it would match empty strings also and it won't match the string with only uppercase letters like FOO.
So this if not re.match("^[a-z]*$", studentName): will return true for all the strings which must not be an empty string or the string which contains only lowercase letters.

You could use a set, and string.ascii_letters:
from string import ascii_letters
def is_all_characters(student_name):
return set(student_name) in set(ascii_letters)

isalpha() works for this requirement.
username = input("Enter Username: ")
if username.isalpha() is False:
print("Only Text allowed in Username")
else:
print("Welcome "+username)

Related

Username and Password validation with user input

Im very new to python and I am creating a user login system, I am currently on a bit of creating a username and password with user input that must meet some conditions e.g
username:
Cannot contain any spaces
Must be at least 5 characters
Cannot include special characters
Your system must display a message to the user telling them what they did wrong if they did not meet
one or more of these criteria (so you will need at least 4 error messages).
My code is as below, but surely theress a better way to do this?
while True:
sNewUser1 = input("""Please enter a new username.
The username must NOT contain any spaces, it must have at least 5 characters and
it cannot include any special characters: \n\n""")
if len(sNewUser1) < 5:
print("Your username is too short, please enter 5 or more characters! Please try again!\n")
elif sNewUser1.count(" ") > 0:
print("Your username contains one or more spaces, this is not allowed! Please try again! \n")
elif sNewUser1.isalnum() == False:
print("Your username contains a special character please try again! \n")
else:
greetuser()
break
while True:
sNewPass1 = input("""\n\nPlease enter a new password.
It must contain:
At least one Capital letter
At least one lower case letter
At least one special character
It has to be at least 6 characters in length:\n\n""")
if len(sNewPass1) < 6:
print("Your username is too short, please enter 5 or more characters! Please try again!\n")
Input prompts can be shortened and more direct.
The whole code should be wrapped in a main() function which is called at the end using the if __name__ == "__main__" condition. This is a convention.
Use is with boolean values, in those conditional statements.
Use the snake_case naming style.
The long strings can be broken into multiple smaller ones.
By now, linters and code-formatters (even Pylint) will not complain about anything.
Your complete code may look something like this, although there is still room for improvement:
"""This is a program for validating usernames and passwords"""
def main():
"""This is the main function"""
while True:
new_user_1 = input("\nPlease enter a new username. "
"It should be at least 5 characters long "
"and not contain spaces or special characters: ")
if len(new_user_1) < 5:
print("Your username is too short. Please try again: ")
elif new_user_1.count(" ") > 0:
print("Your username contains spaces. Please try again: ")
elif new_user_1.isalnum() is False:
print("Your username contains a special character. "
"Please try again: ")
else:
# call another function
break
while True:
new_pass_1 = input("\nPlease enter a new password. "
"It should be 6 characters long "
"with atleast one uppercase letter, "
"one lowercase letter, and one special character: ")
if len(new_pass_1) < 6:
print("\nYour password is too short. Please try again: ")
elif any(lower.islower() for lower in new_pass_1) is False:
print("\nYour password does not contain lowercase letters. "
"Please try again: ")
elif any(upper.isupper() for upper in new_pass_1) is False:
print("\nYour password does not contain uppercase letters. "
"Please try again: ")
elif any(digit.isdigit() for digit in new_pass_1) is False:
print("\nYour password does not contain digits. "
"Please try again: ")
elif any(not char.isalnum() for char in new_pass_1) is False:
print("\nYour password does not contain special characters. "
"Please try again: ")
elif new_pass_1.replace(" ", "") != new_pass_1:
print("\nYour password contains whitespaces. "
"Please try again: ")
else:
# call another function
break
if __name__ == "__main__":
main()
Edit: The previous answer had some bugs. The new one works as intended:
Strings were broken down into smaller ones, but spaces in the end were ommitted.
Simple for loops were used, which checked whether the whole string was uppercase, lowercase, digits, special characters or not, instead of checking each character in the string. The new code fixes this with the use of a built-in function called any. From Python's official documentation:
any(iterable):
Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:
def any(iterable):
for element in iterable:
if element:
return True
return False
Here is an explanation of why/how this works:
elif any(lower.islower() for lower in new_pass_1) means: for any lower in new_pass_1, if lower.islower() returns True, then: code goes here. Therefore, it returns True if any character in the string is lowercase. So if it returns False, it would mean that it did not find any lowercase character in the whole string. The same applies to the checks for uppercase letters and digits.
elif any(not char.isalnum() for char in new_pass_1) means: for any char in new_pass_1, if char.isalnum() does not return True (i.e. the char is a special character), then: code goes here. Therefore, it returns True if any character in the string is a special character (i.e not an uppercase letter, lowercase letter or digit). So if it returns False, it would mean that it did not find any special character in the whole string.
If you're confused about not char.isalnum(): any_string.isalnum() checks whether any_string is alphanumeric or not, i.e whether it is made up of alphabets and numbers only. So inverting it with not char.isalnum() would now check whether any_string is not alphanumeric. And we know that if something is not alphanumeric, it is a special character. Note that this will consider whitespaces to be special characters as well, so I've added a final if statement to check for whitespaces.

Python: How to demand a string as input rather than a specific value

For the YourName input() I would like to get a value that's a string. Hence, it shouldn't be a float, int, etc. In this example I would like to replace "Sunny" with any value that's a string to make the while loop accept the input.
YourName = ''
while YourName != "Sunny":
print("Please type in your name")
YourName = input()
print(YourName + " is correct")
Thanks in advance, best
Sentino
As mentioned in the comments you could use something similar to the following:
YourName = input("Please enter your name: ")
while True:
if YourName.isalpha():
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
isinstance() is a built-in function that checks to see if a variable is of a specific class, e.g. isinstance(my_var, str) == True. However, the Input() function always returns a string. Thus, if you want to make sure the input was all letters you want to use .isalpha(). You could also use Try/except. As #SiHa said this SO question has a great response.
As pointed out in the comments, this answer will not work if there is a space in the string. If you want to allow multiple name formats you can use Regex. for example you can do the following:
import re
YourName = input("Please enter your name: ")
while True:
if re.fullmatch(r"[a-zA-Z]+\s?[a-zA-Z]+", YourName) is not None:
break
else:
print("Must enter string")
print("Please type in your name")
YourName = input("Please enter your name: ")
continue
Using Regular Expressions will give you more control on the inputs than regular string methods. Docs, Python Regex HOWTO. re is a standard library that comes with python and will give you the most flexibility. You can use regex101 to help you test and debug.
What the re.fullmatch() will return a match object if found and None if not. It says the input can be any lower or uppercase letter with an optional space in the middle followed by more letters.
If you don't want to import a package then you can loop through your input object and check to see if all characters are a space or alpha using:
all([x.isalpha() | x.isspace() for x in YourName])
however this will not say how many spaces there are or where they are. It would be optimal to use Regex if you want more control.
It's possible that you're using Python 2.7, in which case you need to use raw_input() if you want to take the input as a string directly.
Otherwise, in Python 3, input() always returns a string. So if the user enters "3#!%," as their name, that value will be stored as a string (You can check the type of a variable by using type(variable)).
If you want to check to make sure the string contains only letters, you can use the method isalpha() and isspace() (in my example code, I'll assume you want to allow spaces, but you can exclude that part if you want to require one word responses).
Because these methods operate on characters, you need to use a for loop:
YourName =""
while YourName is not "Sunny" or not all(x.isalpha() or x.isspace() for x in YourName):
#You can pass a string as a prompt for the user here
name = input("please enter name")
print (YourName)
However, I should note that this check is totally redundant since no string containing a non-letter character could ever be equal to "Sunny".
As others have pointed out, input() always returns a string.
You can use the str.isalpha method to check the character is a letter.
YourName = ''
while True:
print("Please type in your name")
YourName = input()
failed = False
for char in YourName:
if not char.isalpha():
failed = True
if not failed:
break
Example:
Please type in your name
> 123
Please type in your name
> John1
Please type in your name
John
John is correct

How to check if user input is a string

I have two user inputs: in the first one user has to insert a text what is string type and in the second one to insert a number what is int type.
I used try/except ValueError, so user couln't insert a string where int is needed. Although ValueError wouldn't work when user inserts int where string is needed.
How can input value be false, when int is inserted, where str is asked?
This is my code now:
while True:
try:
name_input = input('Insert name')
name = str(name_input)
number = input('Insert number: ')
num = int(number)
except ValueError:
print('Wrong')
If you would like the whole name to be alphabetic you can simply add an if statement like this:
if not name.isalpha():
print("wrong, your name can only include alphabetic characters")
Or better fitting your short example:
if not name.isalpha():
raise ValueError
This will only accept input strings that don't contain any number at all.
If you would like to allow digits in your name as long as the name begins with a letter you could also have something like the following:
if len(name) < 1 or not name.isalnum() or not name[0].isalpha():
raise ValueError
This checks first whether the name is at least 1 character long, then it checks whether the whole name consists solely of alphabetic characters and numbers, followed by a final check to see if the first character is an alphabetic character.
A string with a number in it is still a valid string - it's a string representing that number as text.
If you want to check that the name is not a string composed just of digits, then the following code will work:
while True:
try:
name = input('Insert name: ')
if name.isdigit():
raise ValueError

Changing inputs into titles, issue with handling raw spaces

so I'm quite new to programming and I'm trying to learn python as a starter.
I'm trying to make a function that does multiple things (I'm going to use it for limiting inputs on names).
Rejects purely numerical inputs
Rejects inputs made purely of spaces
Rejects null inputs
Changes the input into a title
def debugstr(inputa):
inputa = inputa.replace(" ", "")
try:
int(inputa)
inputb = debugstr(input("Invalid input, please enter Alphabetic strings only: "))
except:
if inputa == "":
debugstr(input("Invalid input, please enter Alphabetic strings only: "))
else:
return inputa.title()
The issue that I have is that the code will only reject blank inputs on the first try when running the function, if something is rejected once and the user inputs a series of spaces again, then it will just accept it as an input.
Thanks for your time in advance! It's very appreciated :D
A more natural way of handling this (without calling the same function from within itself) is:
def make_title():
def get_user_input():
return input('Enter an alphabetic string: ')
while True:
s = get_user_input()
s = s.strip()
if not s:
print('blank input!')
continue
if s.isdigit():
print('contains only digits!')
continue
return s.title()
print(make_title())
Some notes:
Try not to repeat yourself (e.g. the duplicated error message in your code)
Python contains many useful string methods and s.isdigit() returns True if s contains only numbers
You can strip the whitespace from your input with s.strip() and if you're left with the empty string, '', if not s will be True (the empty string is equivalent to False.
In python 3, you can use isinstance to check if an object is a string.
word = input("Enter string: ")
def checkString(s):
if isinstance(s, str):
print('is a string')
elif not s:
print('empty')
else:
print('not a string')

How do I use isalpha() and isspace()

I am trying to return a yes or no answer to show whether the string has spaces or letters. The bolded part is the part I need to get right. I got the other parts...
Here is what I have put and it doesn't work out correctly...
if (string.isalpha() and string.isspace()):
print('Only alphabetic letters and spaces: yes')
else:
print('Only alphabetic letters and spaces: no')
How can I use them together? I know how to do this separately but not together. I know this may seem really simple but I am a beginner.
example of the program----
Enter a string: please open my email
Length: 20
First character: p
Last character: l
Contains open: yes
Only alphabetic letters and spaces: yes
Only numeric digits: no
All lower case: yes
All upper case: no
You're testing the whole string. You should be testing each character individually.
is_alpha_or_space = all(c.isalpha() or c.isspace() for c in string)
You can use or and all to check each letter:
if all(char.isalpha() or char.isspace() for char in string):
print('Only alphabetic letters and spaces: yes')
Two options:
if all(x.isalpha() or x.isspace() for x in original):
or
original.replace(' ','').isalpha()
should work.
You can try changing the condition to str(input.isspace() and input.isalpha())

Categories