using try and regex in python - python

I'd like to use a try/except statement for checking that a string consists of letters only.
What is wrong with the following
class LetterError(Exception):
pass
name = ""
while name=="":
try:
x = re.match(r'[a-zA-Z]',(input("Please enter a name: ")))
raise LetterError
except LetterError :
print("Insert letters only")

Your regex [a-zA-Z] will match only one character out of given range [a-zA-Z].
I suppose by name you mean multiple characters. Thus use [a-zA-Z]+ for matching multiple characters.

You are raising error in all case. You need to add a condition and also, you don't need your custom error. Regex from here https://stackoverflow.com/a/3617808/5567387
name = ""
while name == "":
name = raw_input("Please enter a name: ")
is_valid = re.match(r'^[a-zA-Z]+$', name)
if not is_valid:
name = ""

Related

How to check if string contains only valid amount of spaces

I need to write code that checks if a certain input string is valid. It must:
Contain a "space" in the input string which separates words
Not contain multiple consecutive spaces in a row
Not contain just a "space" (just
single space as an input).
Here is what I mean:
username = str(input())
print(username)
username = "two apples" # acceptable
username = "two apples and pears" # acceptable
username = "two' '' 'apples" # not acceptable (because of 2 spaces in a row or more)
username = " " # not acceptable (because of single space with no other words.)
username = "' '' '' '' '' '' '" #not acceptable because of multiple spaces (didn't know how to type it in here better to clarify.
I recognize that this might be slightly different than what you are directly asking for, but why not strip the extra spaces from the username input? You could use regex to quickly strip them out per this answer.
If you simply want to return an invalid input, I would again use regex.
import re
username = str(input("Please enter your username: "))
if re.search(" {2,}", username):
print("Please do not include multiple spaces in a row in your username!")
else:
# Do the rest of your program.
I was having my online class, so I couldn't do on time. Now I can give the the answer.
Here's the code. It's pretty simple to understand too.
username = input()
if (" ") in username:
print("Eh!")
elif username.isspace():
print("Ew!")
else:
print(username)
And BTW you don't need to use str() in the input as it takes a string input by default.
Here is the code you are looking for I believe. Please test with different test cases and comment if something is wrong. I tried with all your test cases.
def checkspace(string):
if string:
for idx,i in enumerate(string):
try:
if (string[idx] == ' ' and string[idx+1] ==' '):
return 'String is Not Perfect'
except:
return 'String is Not Perfect'
print('String is Perfect')
else:
return 'No String At AlL'
Eg:
string="two apples"
checkspace(string)
output:
"String is Perfect"
Eg:
string="two apples"
checkspace(string)
output:
"String is Not Perfect"

user input can only be alphabetical characters and includes spaces

I am looking to ask the user to input their first and last name and validate it so that it is only alphabetical letters and spaces and then add it to a text file.
**This is the edited code from your suggestions and it always returns the first print message even though letters have been entered
while True:
new_Book_AuthorFName = input('Enter Author First Name: ')
new_Book_AuthorLName = input('Enter Author Last Name: ')
new_Book_Author_Name = new_Book_AuthorFName + " " + new_Book_AuthorLName
try:
new_Book_Author_Name.replace(' ', '').isalpha()
print("Please Only Use Alphabetical Characters in Name.")
continue
break
except ValueError:
print("Invalid Name.")
Something like this should work:
def include_letter_and_spaces_only(string):
return "".join(string.split(" ")).isalpha()
And then use as:
include_letter_and_spaces_only("test Test Test") # True
include_letter_and_spaces_only("test 12 Test Test") # False
I would do this as.
def lettersOnly(theString: str) -> bool:
"""Determine if a string only contains letters and spaces or not."""
return ''.join(
theString.split(' ')
).isalpha()
Simplest and most pythonic way to be:
def is_alpha_and_spaces_only(string):
return string.replace(' ', '').isalpha()
Faster and more efficient than KetZoomer's approach as it does not require you to (a) split string & (b) combine it back to have result.
P.S. Or just the spirit of the function if you dont want to define that. Just use new_Book_Author_Name.replace(' ', '').isalpha() inplace of if not new_Book_Author_Name.isalpha()

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

How to make input only accept a-z etc

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)

Categories