Convert string with "_" to int? - python

I have a function which takes a string input, tries to convert it to integer and then proceeds with two alternative paths depending on whether the conversion succeeded or not:
def make_int(arg):
try:
int_value = int(arg)
except ValueError:
str_value = arg
I now was quite surprised when the string '123_2307_7' was happily converted to the integer 12323077 - whereas I was expecting it to follow the str path here. What details of str -> int conversion is it I have not yet grokked?

As pointed out by #jonrsharpe the docs says you can embed single _ charcaters in your integer literal - which are simply ignored. Closing.

In python you can write any integer/float this way :
XXX_XXX_XXX
Keep in mind that integer/float are objects in python.

Related

Why does input() only return strings?

My question is very simple, I want to know that when we initialize a variable in python it recognize it whether it is string or integer, But when we use input function it takes input as string and if we need integer or float we have to type cast it. why?
Because input() always returns a str. In another words, input() "recognizes" everything (what is entered to it) as a string.
There is a difference between "123", which is string and 123, which is int. To make int from string, you should use type casting - int(input('Number: ').
input() function is not designed to autodetect type, like Python does, because it is inconvenient default behavior. In all usual cases, a program except certain input type from user. You can implement such thing by yourself (if needed).
Python CAN recognize type of variable. But most of the time python doesn't NEED to.
As mentioned, input always returns str. You need to cast it into int only if you're gonna do something integer-specific with it. In most cases python doesn't care about type of variables. It is called duck typing
https://realpython.com/lessons/duck-typing/

How to check for a string's "natural" datatype in Python?

I have a user inputting arguments to the command line when running a python3 script, and I wish to check whether specific arguments are floats, ints, booleans, or strings. I'm familiar with the errors that are thrown when a string like 'car' is cast to an int using the int() function, and am also familiar with using a try/except block to attempt to cast a string to an int, and if this is unsuccessful, how to map error messages to helpful output to the user. I've also seen this previous question, which will probably do the job. Was just wondering if there had been any new development.
Not sure if this is possible, but looking for a smart type() function that could operate as such:
#!/usr/bin/env python3
import sys
smarttype(sys.argv[-1])
and is capable of handling the following kinds of inputs:
./script.py 50
./script.py True
./script.py 50.0
./script.py run
and output:
int
bool
float
str
I usually use ast.literal_eval to parse “elementary” data types:
type(ast.literal_eval('50')) # outputs int
You need however a set of quotes to mark something as a string (otherwise every input could be taken as a string):
type(ast.literal_eval('run')) # error
type(ast.literal_eval('"run"')) # string
If you want to allow unqouted strings you could do the following:
def parse_data(x):
"""Takes a string x and returns the "value" of x"""
try:
return ast.literal_eval(x)
except (ValueError, SyntaxError):
return x

python argparse hex error

I'm trying to read some hex values i need for my pythonscript using argparser, an example input looks like:
parser.add_argument("start", type=hex, help="hex PC address you want to start recording data")
The problem occurs when i try to start the script with a hexvalue.
example:
python testscript.py 0x21c
Then ik get error:
error: argument start: invalid hex value: '0x21c'
is also tried following values: 0X21C, 21C, 21c, 21. All of them result in the same error.
EDIT: i don't nee the hex value converted to a int. I just need the hex value i inputted. Its a PC address where a µC needs to jump to.
Does anyone know what i'm doing wrong here?
Thanks!
Inspired by:
Convert hex string to int in Python
I tried
In [471]: parser=argparse.ArgumentParser()
In [472]: parser.add_argument('ahex',type=lambda x: hex(int(x,0)))
In [473]: parser.parse_args(['0x21c']) # valid hex string input
Out[473]: Namespace(ahex='0x21c')
In [474]: parser.parse_args(['21']) # converts valid int to hex string
Out[474]: Namespace(ahex='0x15')
In [475]: parser.parse_args(['21c']) # error if string is not valid hex
usage: ipython3 [-h] ahex
ipython3: error: argument ahex: invalid <lambda> value: '21c'
As #mgilson stressed in the comments, the type parameter is a function, one that takes a string and returns something. It also raises an error if the string is not 'valid'. hex() does not work as type, because it takes an integer and returns a hex string. hex('0x21c') is not valid use of that function.
For this quick-n-dirty solution I used a lambda function. It could just as well been a def. I used int(x,0) to convert the string to a int, in a way that handles both hex strings and integer strings. Then I converted that integer back to a string using the hex function.
So the net effect of my lambda is to just validate the hex string. If a valid string it just returns the same thing (same as if type was the default identity lambda x: x).
Confusion over the nature of the type parameter arises most often when people want a boolean value. bool() does not take a string like 'True' or 'False' and return a boolean value. Look up those SO questions if the issue is still confusing.

How to detect and cast string back into right type in Python

In my python server code, I am getting all arguments as strings. I am unaware of the original type of the argument.
For example,
if the actual value is integer 10, the argument received is string value '10'
if the actual value is string "apple". The argument received is unchanged string 'apple'
if the actual value is float 10.0 , the argument received is string value '10.0'
What is the best way to detect the right type of the argument and cast them back to 'int' in the first example, 'string' in the second example, 'float' in the third example?
Ideally, you want to fix the client code so it doesn't throw away type information in the first place. Or, if you can't do that, you at least want to know what the rule is for how these strings are generated, so you can work out how to reverse the rule.
But if neither of those is possible, and you need to guess, one possibility is something like this:
def parseval(s):
try:
return int(s)
except ValueError:
pass
try:
return float(s)
except ValueError:
pass
return s
This will treat anything that could be a valid int as an int, anything that can't be a valid int but could be a valid float as a float, and anything else as a str.
In the special case where the output comes from just calling repr or str in Python, you may want this:
import ast
def parseval(s):
try:
return ast.literal_eval(s)
except ValueError:
return s
This will convert any Python literal, or any collection display made up of literals and other collection displays made up of etc. recursively, to the original value, but leave anything else as itself. (If you know the client is using repr rather than str, you should leave off the try/except. But if it's using str, this works, because it relies on the fact that, for every kind of literal but strings, the str is interpretable as a repr.)
However, note that this makes it impossible to, e.g., send the string "10" to your server.

Convert float to integer in Python - invalid literal error

How do I convert this number to an integer I can do simple math with?!
(eg. 10.5200 below.)
{"bid":["10.52000000","0.70824000"],"ask":["10.54000000","2.07336000"],"seq":2456916}
I get the following error, and it's driving me mental:
ValueError: invalid literal for int() with base 10: '10.52'
This is what I'm running:
bitfl = json.loads(bitfl)
bid = bitfl['bid']
ask = bitfl['ask']
bidd = bid[0] #edit - this is actually in, as it's a list
askk = ask[0]
print('diff: %i' % (int(bidd[0]) - int(askk[0])))
I don't know WHY it should be so difficult to just accept "10.52" as a string or float or unicode and just convert it to a normal, calculable integer!
Any help MUCH appreciated!
The problem is that you are trying to convert a string containing a non-integer to an integer.
The easiest/best solution is using int(float(yourstring))
Since you receive the data as JSON you should also consider requiring whatever client is providing the data not to use strings for non-string data.
Simply write int(float(bidd[0]))

Categories