Check Python String Formatting - python

I can accept user's input in two formats:
123
123,234,6028
I need to write a function/a few lines of code that check whether the input follows the correct format.
The rules:
If a single number input, then it should be just a number between 1 and 5 digits long
If more then one number, then it should be comma-separated values, but without spaces and letters and no comma/period/letter allowed after the last number.
The function just checks if formatting correct, else it prints Incorrect formatting, try entering again.
I would assume I would need to use re module.
Thanks in advance

You can use a simple regex:
import re
validate = re.compile('\d{1,5}(?:,\d{1,5})*')
validate.fullmatch('123') # valid
validate.fullmatch('123,456,789') # valid
validate.fullmatch('1234567') # invalid
Use in a test:
if validate.fullmatch(your_string):
# do stuff
else:
print('Incorrect formatting, try entering again')

Another option is:
def validString(string):
listofints = [v.isdigit() for v in string.split(",") if 0 < len(v) < 6]
if not len(listofints) or not all(listofints):
print("Incorrect formatting, try entering again.")

The following code should leave the Boolean variable valid as True if the entered ibnput complies with your rules and False otherwise:
n = input("Your input: ")
valid = True
try:
if int(n) > 9999:
valid = False
except:
for character in n:
if not character in "0123456789,":
valid = False
if n[-1] == ",":
valid = False

Related

Why doesn't if any(var0) == any(var1) work?

I'm very new to programming, and more new to Python, and I'm having a hard time figuring this out. I'm trying to make a simple text hangman game, and I'm trying to validate player1's input. Here's what I have so far.
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
d = list(d)
print(d)
if any(int) == any(d):
print("Invalid input. Please choose a non-number with no spaces or special characters.")
I can't figure why, whether I include a number in my response or not, it always meets my any(int) == any(d) condition. I know I must just be misunderstanding how any() works.
You are right: the issue is with how you use the any() function. any() returns either True or False depending on whether or not any of the elements in its iterable argument are True, in other words if they exist and are not False or an empty list or empty string or 0. This will always evaluate as True for int because int does contain an element that is True and the same will happen for d unless you do not give any input when the input() function prompts you (you hit return without typing anything). What your conditional is basically asking is the following:
if True==True
To fix this, just change your code to the following:
a = 0
int = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
d = input()
print(d)
for letter in d:
if letter in int:
print("Invalid input. Please choose a non-number with no spaces or special characters.")
break
The easiest solution, however, does not involve the int list at all. There is actually a special method in python that can gauge whether or not a string has a number (or special character) in it, and this method, .isalpha() can be used to streamline this process even further. Here's how to implement this solution:
while True:
d = input("Please choose any word by typing it here: \n")
print(d)
if not d.isalpha():
print("Invalid input. Please choose a non-number with no spaces or special characters.")
Try this:
a = 0
ints = ["1","2","3","4","5","6","7","8","9","0"]
while a == 0:
print("Please choose any word by typing it here:")
word = input()
word_list = list(word)
if any(letter in ints for letter in word_list):
print("Invalid input. Please choose a non-number with no spaces or special characters.")

Given set of numbers in a string in python

I want to check if a set of numbers is present in a string or not
Here is my code:
def check_no(string):
string = string.lower()
no = set(c)
s = set()
for i in string:
if i in no:
s.add(i)
else:
pass
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
c = input()
print(check_no(c))
if the given set of numbers is present in the string then it prints Valid and if not present it prints Not valid
the program works fine when the input is given as 123 and the string is like I have 12 car and 3 bikes then the output is valid
but when i give input as 254 and string as i hav25555number the output comes as valid but the actual output should be Not valid as 4 is not present in the string.
Can anyone help how to solve it in the provided code
I you want to check if all characters match then use all.
def check_no(text, check):
valid = all(character in text for character in check)
if valid:
return("Valid")
else:
return("Not Valid")
check = '254'
text = 'i hav25555number'
print(check_no(text, check))
The one-liner version
def check_no(text, check):
return 'Valid' if all(character in text for character in check) else 'Not Valid'
Your function is mostly correct, but probably because of your (terrible) choices of variable names, string and c variables were mixed up in the environment.
The solution is to add the parameters explicitly to the function definition (also avoid names like string or c as these could be pre-defined python keywords):
teststring = "254"
testc = "i hav25555number"
def check_no(mystring, myc):
string = mystring.lower()
no = set(c)
print("string is",string)
s = set()
for i in string:
if str(i) in no:
# print(i, " in ", no)
s.add(i)
else:
pass
# print("s is",s)
# print("no is",no)
if len(s) == len(no):
return("Valid")
else:
return("Not Valid")
print(check_no(teststring,testc))
gives:
print(check_no(teststring,testc))
string is 254
Not Valid
As mentioned before, you can use all to make your code more elegant, although there is nothing wrong with your implementation either.

Python - Regex - True Or False

So what i want is for my code to understand if my input has a number in it or not, if it does it is meant to output "Correct" but if it doesn't then it would output "Incorrect" how can i actually make this work. So it knows if there is an integer in the input or not. Any help is appreciated
import re
yourString=input()
number = re.search(r'\d+', yourString).group()
if number == True:
print("Correct")
else:
print("Incorrect")
According to https://docs.python.org/3/library/re.html#match-objects you have a bit of a subtle error.
The statement should not be if number == True: it should be if number:, the reason being the value number is tests as True if anything is matched, and is None if there are no matches.
i.e.
import re
yourString=input()
number = re.search(r'\d+', yourString)
if number:
print("Correct")
group = number.group()
else:
print("Incorrect")
Note, somewhat bizarrely
import re
yourString=input()
number = re.search(r'\d+', yourString)
if number:
print(number == True)
group = number.group()
else:
print("Incorrect")
Prints false, so number is not the value true, it overrides __bool__. See https://docs.python.org/3/reference/datamodel.html#object.bool for more information
You can use str.isdigit, re.search, or the built-in string to number conversions such as float and int:
def extractNumber(string):
for word in string.split():
try:
# The float() function accepts a decimal string.
# The int() function accepts an integer string.
return float(word)
except ValueError:
pass
number = extractNumber(input())
if number is not None:
print('Your number is: {}'.format(number))
else:
print('No number found')
the regex you're looking for is: \w*[0-9]+\w*. It accepts anything that contains at least one digit.
\w* is the same as [a-zA-Z0-9_]* meaning it will match any lower/upper -case letter, digit or _ literally. It can occur 0 to many times in the string
[0-9]+ matches one to many digits from 0 to 9.
Actually, if your intention is just to check whether the string has digits you are good to go just with [0-9]+ that's the same of what you posted originally.
You can try and create regexes using this site regex101.com

Checking password input for integers, capitals and lowercase?

I am doing some work for my computing class at school and we need to ask for input of a password. The input needs to be between 6 and 12 characters, and contain uppercase, lowercase and numbers in it. I have this so far :
import sys
import os
def checkPass():
passLoop = True
while passLoop:
print("Welcome user!")
x = len(input("Please enter your password, between 6 and 12 characters. "))
if x < 6:
print("Your password is too short")
r = input("Please press any key to restart the program")
elif x > 12:
print("Your password is too long")
r = input("Please press any key to restart the program")
else:
print("Thank you for entering your password.")
print("Your password is strong. Thank you for entering!")
passLoop = False
checkPass()
I need your help checking for uppercase, lowercase and integers. I'm only young so please don't be too harsh!
^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d).{6,12}$
You can try this.This employs re.
You can use it like
import re
if re.match(r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?\d).{6,12}$",pass,re.M):
print "valid"
else:
print "invalid"
See demo.
http://regex101.com/r/dZ1vT6/28
let's assume you have the password stored in a variable named passwd.
Then we can take your literal requirements and write checks for them:
The input needs to be between 6 and 12 characters,
if not 6 <= len(passwd) <= 12: ...
and contain uppercase,
if not any(c.isupper() for c in passwd): ...
lowercase
if not any(c.islower() for c in passwd): ...
and numbers in it.
if not any(c.isdigit() for c in passwd): ...
On a side note: you really should not limit the length of passwords.
the any function in combination with a map can be helpful. The map function iterates over all characters of the given string and test via the given lambda function if the character is an uppercase. The is consumed by the any function which returns true on the first true from the map function
>>> any(map(lambda a:a.isupper(),"aba"))
False
>>> any(map(lambda a:a.isupper(),"aBa"))
True
you can wrap that into a separate function like
>>> def test(passwd,func):
return any(map(func,passwd))
>>> test("aBa",str.isupper)
True
>>> test("ab0",str.isdigit)
True
>>> test("aBa",str.islower)
True

How to check for valid sequence input?

import re
def check_input():
while True:
try:
sequence = raw_input("Please input:")
if sequence = [a,t,c,g]: # checking for valid input
continue
else:
print("invalid input, sequence coule only contain the "
"following letters (a,t,c,g)"):
check_input()
I basically want the script to check the user's input whether it contains only these four letters (a,t,c,g). If their input contains anything other than that four letters, it could print that second statement and prompt the user to input again. I saw there are similar questions and I already tried to change my script according to those posts but it still gives me the invalid syntax error at the if < sequence position. Anyone knows what's wrong here?
You need to iterate over every letter in the input and check if it is in the set of allowed letters, like this:
sequence = raw_input("Please input:")
for letter in sequence:
if letter not in "atcg":
print("invalid input, sequence coule only contain the following letters (a,t,c,g)")
When you discover that the sequence is invalid, you could choose to end the check by using a break statement after the print, or you could count how many invalid letters are allowed.
Your function must check and give user whether True or False:
def check_input(word):
result = True
for letter in sequene:
if letter in 'atcg':
continue
else:
result = False
break
return result
check_input('atgc')
Error Message:
if check_input('agct'):
continue
else:
print "error message"
You could also use the filter command:
def checkInp():
seq = raw_input("Please input sequence:")
if not filter(lambda m: m not in 'ATGC', seq) == '':
print 'Invalid input characters in sequence: ' + filter(lambda m: m not in 'ATGC', seq)
print 'Pleas'
check_input()
else: return seq
sequence, once input by the user will be a string, so you would need to iterate over each character in the sequence and use in to verify the existence of the character in the accepted characters string. String comparisons in Python are also case sensitive, so you need to match the case of the input to your expected string. I've used uppercase based on your sample input.
def check_input():
sequence = input("Please input:")
sequence.upper()
for letter in sequence:
if letter in 'ATCG':
continue
else:
print("invalid input, sequence could only contain the
following letters: a, t, c or g.")

Categories