This question already has answers here:
How to check if a string only contains letters?
(9 answers)
Closed 7 years ago.
I am trying to validate an input for the user's name. So far I can prevent them entering only numbers and the prompt is repeated using a while loop. How can I stop a string containing letters and numbers being accepted?
This is what I have so far:
name = ""
name = input("Please enter your name:")
while name == "" or name.isnumeric() == True:
name = input("Sorry I didn't catch that\nPlease enter your name:")
Use any and str.isdigit:
>>> any(str.isdigit(c) for c in "123")
True
>>> any(str.isdigit(c) for c in "aaa")
False
In your case:
while name == "" or any(str.isdigit(c) for c in name):
name = input("Sorry I didn't catch that\nPlease enter your name:")
Alternatively you can use str.isalpha:
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
I'd use it like this to validate stuff like "Reut Sharabani":
while all(str.isalpha(split) for split in name.split()):
# code...
What it does is split the input by whitespace and make sure each part is alphabetic letters only.
Related
This question already has answers here:
python - getting 'none' at the end of printing a list [duplicate]
(4 answers)
Closed 8 months ago.
I was looking around and found the re.match to validate a user's input on a phone number. I have the print function there to debug, and it keeps coming back as None type instead of True. Is there a formatting error that I am overlooking?
def validation():
flag = True
while flag:
phone = input('Enter your phone number (XXX-XXX-XXXX): ')
answer = re.match(r'^[0-9]{3}-[0-9]{3}-[0-9]}{4}$',phone)
print(answer)
Basically, I am trying to get the function to validate that the number is in the format XXX-XXX-XXXX and when it is then I can continue, but right now all I am focusing on is returning True on the re.match. The rest of the code I will do after.
You have mistyped '}' in your regex.
Your solution looks correct. This will be the regex to match the phone number format.
re.match(r'^[0-9]{3}-[0-9]{3}-[0-9]{4}$',phone)
And you can write the below code for validation of the phone number and return the boolean value from the function.
import re
def validation(phone):
answer = re.match(r'^[0-9]{3}-[0-9]{3}-[0-9]{4}$',phone)
if(answer is not None):
return True
return False
phone = input('Enter your phone number (XXX-XXX-XXXX): ')
print(validation(phone))
This question already has answers here:
Python how to check if input is a letter or character
(5 answers)
Closed 3 years ago.
I am new to python and trying to figure out how to make this program only take a string or character and then have it spell out said string/character. Unfortunately, when using the lines while word != str() or chr():
word = input("Enter a string or character...") I am constantly prompted to "Enter a string or character" even when I inputted a string/character to begin with. How would I be able to go about fixing this so that the program takes a string and breaks out of the while loop so that it can spell whatever I typed in?
word = input("What is your word? ")
while word != str() or chr():
word = input("Enter a string or character...")
for char in word:
print(char)
Try the following:
word = input("What is your word? ")
while type(word) is not str():
word = input("Enter a string or character...")
for char in word:
print(char)
Also, the input will always be a string.
If you want to check for numeric input, then you should do something like:
try:
int(word)
except ValueError:
# input is a string
else:
continue # input is a number
Maybe something like this would work:
word = input("What is your word? ")
while word.isdigit(): # the word contains only digits
word = input("Enter a string or character...")
for char in word:
print(char)
Few notes:
In your code word != str() would hold true as long as your input is not empty, as str() is a (very ugly) way of initializing an empty string.
The return type from input() is str. If you want to treat it as an integer or any other type you'd have to cast/parse it
This question already has answers here:
How to gather information from user input and apply it elsewhere
(3 answers)
Closed 6 years ago.
Hi I am new to programming and I am trying to write a code that will gather information from the input and determine if it is a valid alphabet.
I previously asked this question before but the answers given just didn't work so I am asking the question again. Please help
words = []
word = input('Character: ')
while word:
if word not in words:
words.append(word)
word = input('Character: ')
print(''.join(words),'is a a valid alphabetical string.')
suppose I choose three letters then the output of my code then pressed enter
on the fourth,
the code will be:
Character:a
Character:b
Character:c
Character:
abc is a valid alphabetical string.
I want to add to this code so that when I type in a character that is not
from the alphabet the code will do something like this.
Character:a
Character:b
Character:c
Character:4
4 is not in the alphabet.
This is exactly how I want my output to be.
If you look at the string class I think you will find it has some variables you would find useful.
from string import letters
word = raw_input("Character: ")
words = []
while word and word in letters:
if word not in words:
words.append(word)
word = raw_input('Character: ')
I don't have python on this computer but I think that you will find this chunk of code works. Also, the string class has a several other variables you might find useful including digits, punctuation, printable etc
You may use string.isalpha() function to find whether the input is alphabetic or not.
>>> 'a'.isalpha()
True <-- as 'a' is alphabet
>>> 'A'.isalpha()
True <-- as 'A' is also alphabet
>>> ''.isalpha()
False <-- empty string
>>> '1'.isalpha()
False <-- number
-------------------------
>>> 'ab'.isalpha()
True <-- False, since 'ab' is alphabetic string
# NOTE: If you want to restrict user to enter only one char at time,
# you may add additional condition to check len(my_input) == 1
>>> len('ab') == 1 and 'ab'.isalpha()
False
In order to get the input from user, you can do:
Using raw_input:
x = raw_input() # Value of x will always be string
Using input
x = input() # Value depends on the type of value
x = str(x) if x else None # Convert to str type. In case of enter with value set as None
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!")
This question already has answers here:
How to check if a string only contains letters?
(9 answers)
Closed 8 years ago.
I am making a program whereby a user can enter their personal details, such as first name, last name and date of birth, and this data gets saved in a separate text file. I need to make a format check to ensure the first and last name entered by the user is a string, i.e. no numbers in between.
I have used a try: except: to ensure the data input for weight is in a specified range and isn't a character.
valid = False
while not valid:
try:
weight = int(input("what is your weight?: "))
if 50 <= weight <= 100:
valid = True
else:
print("please enter sensible weight")
except ValueError:
print("please enter valid weight")
Do not reinvent the wheel, your python version already has this capabilities:
>>> 'abc'.isalpha()
True
>>> '123'.isalpha()
False
>>> 'ab1c'.isalpha()
False
>>> '123'.isalnum()
True
>>>
To check if a given string has any digit we can use :
DIGITS = ['1','2','3','4','5','6','7','8','9','0']
def check_digits(sample_string):
for character in sample_string:
if character in DIGITS:
return False
return True
Note that you can always change the DIGITS list to include any unwanted character.