How to check if user input is a string - python

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

Related

'except ValueError' is not executing

I am trying to ask the user for a string only but whenever the user types an integer or a float, it does not execute the except ValueError code.
Here is my code:
word = input('Enter a string.')
try:
word1 = str(word)
print(word1)
print(type(word1))
except ValueError:
print('The value you entered is not a string.')
The function input always returns a string. you can check if the input is a number in one of the following ways:
Use build in methods in str Class:
word = input('Enter a string.')
# Check if the input is a positive integer without try except statements:
if word.isnumeric():
# The word contain only numbers - is an positive integer.
print("positive int")
Try convert the variable in try expect statement:
word = input('Enter a string.')
# Check if the input is a positive integer with try except statements:
try:
word = float(word)
print("the input is a float")
except ValueError:
print("the input is a string")
input() function in python always takes input as string only. So your code will never throw an exception.
The valueError will catch the error in this case -> int(word). Where word does not contain a pure number.
Always include your statements in double-quotes. Eg.
input("Enter the name: ")
Good, you asked this doubt. It's always good to ask for mistakes.
By defaults input function in python consider your input as "string " whatever enter code hereyou type it is string .
for converting your input into integer you have to type this code .
word = int(input('Enter a string.'))
try:
word1 = str(word)
print(word1)
print(type(word1))
except ValueError:
print('The value you entered is not a string.')
In this case your code is working .

The catch_error_str function isn't catching errors when the input is a integer. - Python

Please don't be too harsh because I'm new to coding. The problem I'm having is that the function catch_error_str does not work. For example, when I enter "2" as an input then it says last_name is 2 instead of catching the error.
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
def surname ():
print("What is the surname of the lead booker ")
last_name = catch_error_str()
print(last_name)
print("Welcome to Copington Adventure Theme Park's automated ticket system\nplease press any button to see the ticket prices.")
enter = input()
print("\nAdult tickets are £20 each \nChild tickets are £12 each \nSenior citizen tickets are £11 each")
surname()
Python don't have a problem to covert a number to a string and because of that, there is no error rasing.
You can try
def catch_error_str():
unvalid = True
while unvalid:
try:
string = str(input())
if not string.isalpha():
raise ValueError
unvalid = False
return string
except ValueError:
print("You must not enter any numbers")
The isalpha() method of string will check if the input not containing numbers and if so it will raise the value error.
The value that is returned from Input() is of type str therefore, the conversion won't generate an error that you can catch with ValueError. Instead you should try to check the type() of the variable. Also, you are requiring the input within the try. I would use something like this:
def catch_error_str():
unvalid = True
while unvalid:
string = input()
try:
string = float(string)
print("You must not enter any numbers")
except ValueError:
unvalid = False
return string
Since floats/ints can be converted to strings without any problem, I'm facing the problem the other way around. I am trying to convert it into a float, if I'm able to, it's because the value is numeric, hence the error. If I am not able to, then that means it will generate ValueError because it is text
Input returns a string even if the user input is a digit.
name = input(“Enter last name: “)
if name.isdigit():
unvalid = True
If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.
https://docs.python.org/3/library/functions.html#input

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

using try and regex in 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 = ""

How to check if every character of the string is different?

I was just wondering, how to check if I ask a person to input a string, how do I check if every character inside that string is different?
For an example:
string = str(input("Input a string: ")
I would like to do it with a while loop. So, if two characters in a string are different, it stays in the loop and prompts the user to input the string again.
If I understand your question correctly, you want to reject any string that contains more than one copy of the same character. If a string with duplicated characters is entered, you want to repeat the prompt and get another input.
The easiest way to do the duplicate check is to create a set from your string and then check if the set has the same length as the original. If there were any duplicates in the string, they'll be present only once in the set.
while True:
input_string = input("Enter a string")
if len(set(input_string)) == len(input_string):
break
print("Please avoid repeating any characters")
You could also try this:
while True:
b = input("Enter a string: ")
if all([b[i] not in b[:i] + b[i+1:] for i in range(len(b))]):
break
print("Please try again!")

Categories