Is there any possible direct way to convert 345., which is actually a str type, to int type?
I tried int('345.') but it gives:
ValueError: invalid literal for int() with base 10: '345.'
Probably not very elegant, but does what you want without modifying your string:
int(float('345.'))
Ugly solution, but works :)
int('365.'.split('.')[0])
I think it is understandable first delete the last char then convert it to float.
fl = "345."
fl = fl[:-1]
fl = float(fl)
Related
This is pretty well documented but I keep getting output that doesn't make sense. I have a hex value that looks like
\x00\x00\x00\x00\x00\x01\x86\xa0
but I get
>>> b'\x00\x00\x00\x00\x00\x01\x86\xa0'.hex()
'00000000000186a0'
I am expecting a int or at least a readable number. I assume I am using the wrong function.
Advice?
You need to add a base value of 16
For Example
hex_string = "a1"
integer = int(hex_string, 16)
print(integer)
The output of this will be 161
Try this out
Then try this
hex_bytes = b'\x12\x34'
integer= int.from_bytes(hex_bytes,byteorder='big')
print(integer)
I have an ID DIS002789.I want to extract 2789 from the given ID.I have to use the extracted number in a for loop using a variable.
I tried using re.findall.
inputk='DIS0002789'
non_decimal = re.findall(r'[\d.]+', inputk)
for n in range(non_decimal, non_decimal + 1000):
Im getting 002789. But I want my output to be 2789.And also i cant use the for loop because of this.It shows a n error saying 002789 is an invalid syntax.
I tried converting it to int. but its shows the following error,
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'
you can pass the result of re.findall(r'[\d.]+', inputk) to int in order to make it an integer. int('0123') will ignore leading zeroes.
Example:
inputk='DIS0002789'
non_decimal = int(re.findall(r'[\d.]+', inputk))
if you want it to be a string you can pass it to str again: str(int('0123')) == '123'
If you want the int value, you should convert it to integer as other answers show. If you only want the string, you can try adding the optional leading zeros:
inputk='DIS0002789'
non_decimal = re.findall(r':?[0]*(\d+)', inputk)
non_decimal
output:
['2789']
you can ignore leading zeros and convert it to an integer to use in a loop
inputk='DIS0002789'
non_decimal = int(re.findall(r':?[0]*(\d+)', inputk)[0])
how convert float to int to string?
with open(DATA_DIR+'/test.csv', 'r') as inp:
reader = csv.DictReader(inp, delimiter=',',fieldnames = ['Id', 'Target'])
for row in csv.reader(inp):
text_file.write("Text "+str(int(row[1])))
Error: ValueError: invalid literal for int() with base 10: '323.0'
EDIT: The CSV parser is already reading the data that you are trying to convert as a string. That string has decimal point values which it won't convert to int. It will convert it to float though.
Here are 2 ways to do this:
Just split the string and use the integral part
in your example do text_file.write('Text {:.0f}'.format(float(row[1]))
With the 2nd approach you are basically converting it to float and thereafter you don't care for anything on the right of the decimal. So .0f indicates you don't want anything after the decimal including the .. More on this formatting can be learned in the link I pasted below.
As you dig deeper you should continue to use type() to identify the incoming data before you decide what to do with it.
ORIGINAL PART:
You don't have to convert the data to achieve what you want. At the end of it you want to write to a file as a string. If what you are getting from the csv is a float then you could simply format your string as
write_line = 'Text {:06.2f}'.format(row[1])
text_file.write(write_line)
Of course you could condense the two lines.
There is more info in python's docs - https://docs.python.org/3/tutorial/inputoutput.html
x=Decimal(row[1]).normalize()
text_file.write(x)
Probably looks like row[1] is not having any numeric value. Can u specify what exactly it will hold?
Try printing row[i] before executing the int() function and see what value it is holding.
I feel like a complete tool for posting this, it is so basic and I cant believe I have wasted the last two days on this problem. I've tried all the solutions I can find on this (seriously, I will show you my internet history) but to no avail. Here is the problem:
I am parsing a serial string in from a uC. It is 52 bytes long and contains a lot of different variables of data. The data in encoded in packed binary coded decimal.
Ex: .....blah.....0x01 0x5E .....blah
015E hex gives 350 decimal. This is the value I want. I am reading in the serial string just fine, I used binascii.hexifiy to print the bytes to ensure it is corrent. I use
data = ser.read()
and placed the data in an array if an newline is not received. I have tried making the array a bytearray, list, anything that I could find, but none work.
I want to send the required two byte section to a defined method.
def makeValue(highbyte, lowbyte)
When I try to use unpack, join, pack, bit manipulation, string concentation, I keep getting the same problem.
Because 0x01 and 0x5E are not valid int numbers (start of heading and ^ in ASCII), it wont work. It wont even let me join the numbers first because it's not a valid int.
using hex(): hex argument can't be converted to hex.
Joining the strings: invalid literal for int() with base 16: '\x01^'
using int: invalid literal for int() with base 10: '\x01^'
Packing a struct: struct.error: cannot convert argument to integer
Seriously, am I missing something really basic here? All the examples I can find make use of all the functions above perfectly but they specificy the hex numbers '0x1234', or the numbers they are converting are actual ASCII numbers. Please help.
EDIT
I got it, ch3ka set me on the right track, thanks a million!
I don't know why it wouldn't work before but I hex'ed both values
one = binascii.hexlify(line[7])
two = binascii.hexlify(line[8])
makeValue(one, two)`
and then used the char makeValues ch3ka defined:
def makeValue(highbyte, lowbyte)
print int(highbyte, 16)*256 + int(lowbyte, 16)
Thanks again!!!
you are interpreting the values as chars. Feeding chars to int() won't work, you have to feed the values as strings, like so: int("0x5E", 16). What you are attempting is in fact int(chr(int("0x5E", 16)),16), which is int("^",16) and will of course not work.
Do you expect these results?
makevalue('0x01', '0x5E') -> 350 0x15e 0b101011110
makevalue('0xFF', '0x00') -> 65280 0xff00 0b1111111100000000
makevalue('0x01', '0xFF') -> 511 0x1ff 0b111111111
makevalue('0xFF', '0xFF') -> 65535 0xffff 0b1111111111111111
If so, you can use this:
def makeValue(highbyte, lowbyte):
return int(highbyte, 16)*256 + int(lowbyte, 16)
or the IMO more ugly and errorprone:
def makeValue(highbyte, lowbyte):
return int(highbyte+lowbyte[2:], 16) # strips leading "0x" from lowbyte be4 concat
When trying to convert a string into integer to be used as a variable later in the code, I get the following:
print int(urlsuccessful[i])
ValueError: invalid literal for int() with base 10: '2,919,247'
locale.atoi() will "demark" integers based on the current locale setting.
If only problems are commas, try:
>>> int("2,919,247".replace(",", ""))
2919247
int does not understand commas, you'll want to remove those before trying to convert
You can just do
def int2str(my_integer):
return "%d" % my_integer