General Python Programming 2.7 data validation - python

I was wondering what functions should I use for this def function so that the user can only enter strings and not integers -
def GetTextFromUser():
TextFromUser = raw_input('Please enter the text to use: ')
return TextFromUser

raw_input() always returns a string. But ,if by string you meant only alphabets are allowed, then you can use: str.isalpha()
S.isalpha() -> bool
Return True if all characters in S are alphabetic
and there is at least one character in S, False otherwise.
examples:
In [9]: 'foo'.isalpha()
Out[9]: True
In [10]: 'foo23'.isalpha()
Out[10]: False

According to the documentation, raw_input always returns a string. If you never want it to return an integer, I would try to convert it to an integer using int() and catch an exception if it fails. If it doesn't fail, immediately after, return the value. This follows the Pythonic style of "it's better to ask for forgiveness than for permission."

Related

I want to distinguish between true digit and a string digit

I want to check a 'x' string whether it is a digit or not in advance.
'1' is naturally a digit.
But and I will use ① what is calld a string number very much.
I don't know the range of string numbers IDE judges as a digit.
'①'.isdigit() returns True.
'⑴'.isdigit() returns True.
'ⅰ' or 'Ⅰ' returns False.
'㈠' returns False. (kanji version of (1) )
'❶' returns True.
I want to do like this.
for s in data:
if s.isdigit():
int_ = int(s)
If I accept '①', int will throw an error. Now, I write try:except for it.
Because I'm a japanese, I often use '①' or '⑴'
How to distinguish isdigit or not isdigit in advance?
Should I rely on try:except or counting all of them in advance?
regular expression?
The main problem is I don't know what is judged as a digit.
data = ["1", "23", "345", "①", "(1)", "(2)"]
This data is dynamic value. It will be changed every time.
Moreover, the string like this may expand in the future.
I hope the string of isdigit() == True is accepted by int().
I don't have an urgent problem because of try: except.
I believe that the str.isdecimal method fits your requirements. It excludes strings like '①', but includes other strings like '١' which are accepted by int.
>>> int('١')
1

Is there a way to check if every character in a string conforms to the set RE conditions?

I've been re-learning python over the last 2 days, and decided to use regular expression [here out referred to as RE] for the first time (in conjunction with tkinter), its exceptionally confusing.
I'm trying to check every character in a string is a number or period, however this has proven difficult for me to wrap my head around.
Here is the code:
def matchFloat(string, search=re.compile(r'[0-9.]').search):
return bool(search(string))
def matchInt(string, search=re.compile(r'[0-9]').search):
return bool(search(string))
def callbackFloat(P):
if matchFloat(P) or P == "":
return True
else:
return False
def callbackInt(P):
if matchInt(P) or P == "":
return True
else:
return False
The first character entered into my enter box [see below] is forced to be a number or . (in the Floats case), however RE search() only requires 1 of the characters to meet the conditions for it to return True.
So in short, Is there a way to only return True if every character in a string conforms to the set RE conditions?
Any help is appreciated, thank you in advanced!
Images:
As you can see, I'm quite new to this.
Disallowed Characters In Box
This thread may be helpful as it covers the topic of tkinter input validation.
However, quick answer to your question:
search(r"^[0-9]+$", string)
would match an integer string. The RE pattern means "one or more digits, extending from the beginning of the string to the end". This can also be shortened to r"^\d+$".
You could also use the re.fullmatch() method:
fullmatch(r"[0-9]+", string)
And for the sake of completeness, I'll point out that you don't need to do this work yourself. You can determine if a string represents an integer with string.isdigit(), string.isdecimal(), or string.isnumeric() methods.
As for checking whether a string is a float, the Pythonic way is to just try converting to a float and catch the exception if it fails:
try:
num = float(string)
except:
print("not a float")

Why does the str.isdigit always output the opposite result

def is_valid_zip(zip_code):
"""Returns whether the input string is a valid (5 digit) zip code
"""
if (len(zip_code) == 5) and (str.isnumeric == True):
return True
else :
return False
First of all, it should be str.isnumeric() == True as that's calling the isnumeric function. Second of all you should be really using str.isdigit().
str.isnumeric()
In Python, decimal characters (like: 0, 1, 2..), digits (like: subscript, superscript), and characters having Unicode numeric value property (like: fraction, roman numerals, currency numerators) are all considered numeric characters. Therefore even japanese character for 1, 2 and 3 would pass this check.
str.isdigit()
On the other hand isdigit() will only return True if all characters in a string are digits. If not, it returns False.
source: https://www.programiz.com/python-programming/methods/string/isdigit
A few point to discuss. Regarding your condition:
str.isnumeric == True
That thing on the left side is the function itself, not a call to the function giving a result, the latter would be some_string.isnumeric().
The chances of the function object being equal to true are somewhere between zero and a very, very small number :-)
It's also redundant to compare boolean values against boolean constants since the result of the comparison is just another boolean value. Where do you stop in that case? For example:
(((some_bool_value == True) == True) == True) != False ...
Another point, the code form if cond then return true else return false can be replaced with the much less verbose return cond.
And also keep in mind that isnumeric() allows other things than raw digits, like ¾. If you just want the digits, you're probably better off with another method. You may be tempted to instead use isdigit(), but even that allows other things than just what most would consider "normal" digits, such as allowing "90²10" as a postal code, presumably the much trendier part of Beverly Hills :-).
If you only wanted the raw digits 0-9 (which is probably the case with US postal codes like you seem to be targeting), neither isnumeric() nor isdigit() is really suitable.
An implementation of the function, taking all that into account, could be as follows:
def is_valid_zip(zip_code):
if len(zip_code) != 5:
return False
return all([x in "1234567890" for x in zip_code])
it should be zip_code.isnumeric() not str.isnumeric
Also, why don't you use regex:
import re
RE_ZIP_CODE = re.compile(r'^[0-9]{5}$') # or r'^\d{5}$' for all digit characters
def is_valid_zip(zip_code):
return RE_ZIP_CODE.search(zip_code) is not None
This should work
def is_valid_zip(zip_code):
"""Returns whether the input string is a valid (5 digit) zip code
"""
if len(zip_code) == 5 and zip_code.isnumeric():
return True
else:
return False
print(is_valid_zip("98909"))

How can I check if a users input is strictly alphabetical?

I am currently working on the pseudocode of a project and it has just come to mind that, while I have a way of checking if User Input is strictly numerical, I have no idea of how to check if the input is strictly Alphabetical.
For Example:
def valueCheck_Int(question):
while (True):
try:
return int(input(question))
except:
question = "That is not a valid integer, try again: "
def main():
userInput = valueCheck_Int("Enter an integer: ")
print(userInput)
main()
This piece of code checks if the user's input is strictly numerical, and will only break the loop until the user has entered an integer.
Is there any possible way to do this, but with string input being alphabetical, with no numbers at all?
The str type in Python have methods for checking it, you don't need try, except at all.
These methods called isnumeric and isalpha.
isnumeric - If a string is a number, it'll return True, otherwise return False.
isalpha - If a string is alphabetical, it'll return True, otherwise return False.
Code Example:
string = 'alphabetical'
if string.isnumeric():
print('String is numeric!, it contains numbers and valid for integer casting!')
elif string.isalpha():
print('String is alpha!, it contains alphabetical letters.')

python - str containing whitespace characters and int(str)

I'm trying to write a really simple function. It should return True if given object is a digit (0-9), False otherwise. Here are examples of input and desired output:
is_digit("") => False
is_digit("7") => True
is_digit(" ") => False
is_digit("a") => False
is_digit("a5") => False
My code works for the above examples.
def is_digit(n):
try:
return int(n) in range(0, 10)
except:
return False
Trouble is, the function returns True for n = "1\n" when it should return False. So, a string like "1" should be converted to integer and is a digit, but a string like "1\n" should not, yet I don't know how to get around that. How can I account for string literals?
P.S. If my title is lame, advice on renaming it is welcome.
You don't need to define a custom function for this. There is a built-in function for this, namely isdigit().
You can use it as: "a5".isdigit() or "1/n".isdigit().In both cases it will return False.
First you have to convert your literals into string then you can apply isdigit.
You can not apply isdigit directly to number. It will throw an error
AttributeError: 'int' object has no attribute 'isdigit'
You have to typecast your number in string.
eg:
In [3]: str(0).isdigit()
Out[3]: True
or
In [1]: "0".isdigit()
Out[1]: True

Categories

Resources