d = input("1 - to enter expression; 2 - to enter text; 3 - to exit. ")
try:
d = int(d)
except ValueError:
d = 3 # the default value
Answer from Ionut Hulub on Stack OverflowI was confused by the fact that int("012") equals 12 but int("0o012") results in an error. I would have expected the opposite. Reading the documentation for int() I learned that if the base is set to zero int() the input is treated like a literal int (e.g. int("0o012") = 10).
Intuatively I would expect int() to treat input as a literal interger in Python and that it should know "0o012" is base 8 just like if I used as a literal.
Why would the default be base = 10? Except for the leading 0 case doesn't base = 0 cover all base = 10 cases, plus lets you use "0b", "0o", and"0x".
My question is why the default value for base inint() is 10 rather than 0 which seems to be the more.
If you want a one-liner like you've attempted, go with this:
variable = int(stringToInt) if stringToInt else None
This will assign variable to int(stringToInt) only if stringToInt is not empty AND is "numeric". If, for example stringToInt is 'mystring', a ValueError will be raised. If stringToInt is empty (''), it will assign variable to None.
To avoid ValueErrors, use a try-except:
try:
variable = int(stringToInt)
except ValueError:
variable = None
I think this is the clearest way:
variable = int(stringToInt) if stringToInt.isdigit() else None
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
Python2 method to check if a string is a float:
def is_float(value):
if value is None:
return False
try:
float(value)
return True
except:
return False
For the Python3 version of is_float see: Checking if a string can be converted to float in Python
A longer and more accurate name for this function could be: is_convertible_to_float(value)
What is, and is not a float in Python may surprise you:
The below unit tests were done using python2. Check it that Python3 has different behavior for what strings are convertable to float. One confounding difference is that any number of interior underscores are now allowed: (float("1_3.4") == float(13.4)) is True
val is_float(val) Note
-------------------- ---------- --------------------------------
"" False Blank string
"127" True Passed string
True True Pure sweet Truth
"True" False Vile contemptible lie
False True So false it becomes true
"123.456" True Decimal
" -127 " True Spaces trimmed
"\t\n12\r\n" True whitespace ignored
"NaN" True Not a number
"NaNanananaBATMAN" False I am Batman
"-iNF" True Negative infinity
"123.E4" True Exponential notation
".1" True mantissa only
"1_2_3.4" False Underscores not allowed
"12 34" False Spaces not allowed on interior
"1,234" False Commas gtfo
u'\x30' True Unicode is fine.
"NULL" False Null is not special
0x3fade True Hexadecimal
"6e7777777777777" True Shrunk to infinity
"1.797693e+308" True This is max value
"infinity" True Same as inf
"infinityandBEYOND" False Extra characters wreck it
"12.34.56" False Only one dot allowed
u'四' False Japanese '4' is not a float.
"#56" False Pound sign
"56%" False Percent of what?
"0E0" True Exponential, move dot 0 places
0**0 True 0___0 Exponentiation
"-5e-5" True Raise to a negative number
"+1e1" True Plus is OK with exponent
"+1e1^5" False Fancy exponent not interpreted
"+1e1.3" False No decimals in exponent
"-+1" False Make up your mind
"(1)" False Parenthesis is bad
You think you know what numbers are? You are not so good as you think! Not big surprise.
Don't use this code on life-critical software!
Catching broad exceptions this way, killing canaries and gobbling the exception creates a tiny chance that a valid float as string will return false. The float(...) line of code can failed for any of a thousand reasons that have nothing to do with the contents of the string. But if you're writing life-critical software in a duck-typing prototype language like Python, then you've got much larger problems.
You can't really specify it directly in the argument field, but you can convert it right after the function declaration:
def profile(request, pk=0):
pk = int(pk)
#to do
It will throw an error if the passed value for pk cannot be converted to an int
EDIT: I spoke too soon, apparently you can do exactly as you did, just change things around:
def profile(request, pk: int = 0):
#to do
BTW: I just did a quick research for "specify type of argument python". Please try to research easy things like so first before asking a question, you'll get an answer quicker :)
My code works for any input type of pk: integer, string with integer, string without integer
import re
def intCheck(pk):
contains_number = bool(re.search(r'\d', pk))
if contains_number:
return int(re.search(r'\d+', pk).group())
else:
return 0
def profile(request, pk=0):
pk = intCheck(pk)
print(request + " " + str(pk))
profile('request', "232")
profile('request', 123)
profile('request', "no number")
Output:
request 232
request 123
request 0