This question already has answers here:
How to use digit separators for Python integer literals?
(4 answers)
Closed 3 years ago.
Unable to convert a string to an integer. Getting Error:
ValueError: invalid literal for int() with base 10: '2674'
I have read many answers and most of them the reason for not working is because it is a float and people use int(), but here clearly it is an integer.
like1 = '2,674 likes'
number = int(like1.split()[0])
print('This is the numer ::',number)
I expect the code to run without an error and print out the number. My actual implementation is to compare it with an integer. For eg. number > 1000, but that throws up the error that you can't compare a string and int, therefore I wanted to modify it into an int. I did not want to post that code since it was pretty big and messy.
Please ask for clarifications, if I have missed any required details!
Your problem is the comma in 2,674. Some locations use that as a decimal point, but your location does not, and you want it to separate groups of three digits in an integer. Python does not use it in that way.
So either remove the comma or change it to an underscore, _, which recent versions of Python allow in an integer. Since I do not know your version of Python I recommend removing the comma. Use this:
number = int(like1.split()[0].replace(',', ''))
By the way, the error message you show at the top of your question is not the actual error message. The actual message shows the comma in the string:
ValueError: invalid literal for int() with base 10: '2,674'
If you continue asking questions on this site, be sure to show the actual errors. In fact, you should copy and paste the entire traceback, not just the final line. That will help us to correctly understand your problem and help you.
Related
This question already has answers here:
Counterintuitive behaviour of int() in python
(4 answers)
Closed 3 years ago.
In python, when converting strings to floats, float() converts both integers or decimals representations to a number:
float('3.5') gives 3.5
float('3') gives 3
float() also converts integers to floats:
float(3) gives 3.0
Why does int() not convert a string decimal to an integer if it can convert a float to an integer? For example:
int(3.5) gives 3,
however int('3.5') raises an ValueErrorexception.
This makes one use something like int(float('3.5')) when wanting to convert a string into an integer while not knowing whether or not the number will be a decimal.
Why is there this difference between float() and int()?
I would say, why not?
This is more like a precaution of conversion. It tries to be careful and conservative as conversion can lost data precision in an unexpected way. By saying int(float("3.5")), your intention is explicit. But int("3.5") -- do you expect that is not an integer and you are ready to give up that 0.5 difference? Such issue does not exists in float("3.5").
If you want int("3.5") to give you back the integer without raising error, would it be natural to also ask for int("four"), int("3.5 # ignore this comment"), int("XLII") to be valid? That would be too much.
So I have a String called 'Number' with 'abf573'. The task is, to find out if the String 'Number' just has characters and numbers from the Hexadecimal System.
My plan was to make a for loop, where we go through each position of the String 'Numbers', to check with an if statement if it is something out of the Hexadecimal System. To check that, I thought about writing down the A-F, a-f and 0-9 into Lists or separat Strings.
My Problem now is, that I have never done something like this in Python. I know how to make for loops and if-/else-/elif-Statements, but I dunno how to implement this in to this Problem.
Would be nice, if someone can give me a hint, how to do it, or if my way of thinking is even right or not.
I find it quite smart and fast to try to convert this string into an integer using int(), and to handle the exception ValueError which occurs if it is not possible.
Here is the beautiful short code:
my_string = 'abf573'
try:
result = int(my_string, 16)
print("OK")
except ValueError:
print("NOK")
Strings are iterables. So, you can write
Number = '12ab'
for character in Number:
if character in 'abcdef':
print('it is HEX')
Also, there is an isdigit method on strings, so your number is hex is not Number.isdigit()
So when I run:
value = long("00000000000000020000000000000002", 16)
I get :
ValueError: Value out of range: 36893488147419103234
I think it's because long can't take such a big hex number, but I'm not sure.
In reality I'm iterating through a file with a large amount of very big hex numbers, but this is just an example of one of the hex numbers I'm trying to parse.
I've tried using lstrip() to remove some of the 0's but it made no difference to the error.
What am I doing wrong?
The error was being caused by the variable I was trying to assign the value to, not the actual long() function.
I am extracting a string out of a JSON document using python that is being sent by an app in development. This question is similar to some other questions, but I'm having trouble just using x = ast.literal_eval('[0448521958, +61439800915]') due to the plus sign.
I'm trying to get each phone number as a string in a python list x, but I'm just not sure how to do it. I'm getting this error:
raise ValueError('malformed string')
ValueError: malformed string
your problem is not just the +
the first number starts with 0 which is an octal number ... it only supports 0-7 ... but the number ends with 8 (and also has other numbers bigger than 8)
but it turns out your problems dont stop there
you can use regex to fix the plus
fixed_string = re.sub('\+(\d+)','\\1','[0445521757, +61439800915]')
ast.literal_eval(fixed_string)
I dont know what you can do about the octal number problem however
I think the problem is that ast.literal_eval is trying to interpret the phone numbers as numbers instead of strings. Try this:
str = '[0448521958, +61439800915]'
str.strip('[]').split(', ')
Result:
['0448521958', '+61439800915']
Technically that string isn't valid JSON. If you want to ignore the +, you could strip it out of the file or string before you evaluate it. If you want to preserve it, you'll have to enclose the value with quotes.
This question already has answers here:
How can I check if a string represents an int, without using try/except?
(23 answers)
Closed 9 years ago.
I have an application that has a couple of commands.
When you type a certain command, you have to type in additional info about something/someone.
Now that info has to be strictly an integer or a string, depending on the situation.
However, whatever you type into Python using raw_input() actually is a string, no matter what, so more specifically, how would I shortly and without try...except see if a variable is made of digits or characters?
In my opinion you have two options:
Just try to convert it to an int, but catch the exception:
try:
value = int(value)
except ValueError:
pass # it was a string, not an int.
This is the Ask Forgiveness approach.
Explicitly test if there are only digits in the string:
value.isdigit()
str.isdigit() returns True only if all characters in the string are digits (0-9).
The unicode / Python 3 str type equivalent is unicode.isdecimal() / str.isdecimal(); only Unicode decimals can be converted to integers, as not all digits have an actual integer value (U+00B2 SUPERSCRIPT 2 is a digit, but not a decimal, for example).
This is often called the Ask Permission approach, or Look Before You Leap.
The latter will not detect all valid int() values, as whitespace and + and - are also allowed in int() values. The first form will happily accept ' +10 ' as a number, the latter won't.
If your expect that the user normally will input an integer, use the first form. It is easier (and faster) to ask for forgiveness rather than for permission in that case.
if you want to check what it is:
>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False
if you want to get ints from raw_input
>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
except: pass
>>>isinstance(x,int)
True
The isdigit method of the str type returns True iff the given string is nothing but one or more digits. If it's not, you know the string should be treated as just a string.
Depending on your definition of shortly, you could use one of the following options:
try: int(your_input); except ValueError: # ...
your_input.isdigit()
use a regex
use parse which is kind of the opposite of format
Don't check. Go ahead and assume that it is the right input, and catch an exception if it isn't.
intresult = None
while intresult is None:
input = raw_input()
try: intresult = int(input)
except ValueError: pass