Keep zero digit save while converting string to integer in python - python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.
string_value = '0123'
print(int(string_value))
result is 123
How can i format output 0123 as in integer type value not in string.

You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.
"{:04}".format(123)
# '0123'
"{:05}".format(123)
# '00123'

Like every one said you can try above answers or the following :
string_value = '0123'
int_no = int(string_value)
print("%04d" % int_no)
print(string_value.zfill(4))
Both will give same answer

Impossible, you cannot get an integer value of 0123.
You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

Related

How to grab hex value in between a bunch of zeros and convert it to decimal?

I wanted to try and grab a hex value in between a bunch of zeros and convert it to decimal. Here's a sample: '00000000002E3706400000'. So I only want to grab '2E37064' and disregard everything else around it. I know to use the int() function to convert it to decimal, but when I do, it includes the leading zeros right after the actual hex value. Here's a sample of my code:
hex_val = '00000000002E3706400000'
dec_val = int(hex_val, 16)
print(dec_val)
And then here's the output:
50813862936576
The actual value I want is:
48459876
Is there an optimal way to accomplish this?
You can use the .strip() function to remove the leading and trailing zeroes (though removing the leading zeroes here isn't technically necessary):
int(hex_val.strip('0'), 16)
This outputs:
48459876

Convert Value to 32-bit values

I have a table Widget and user give a number in table, so when I get this value I want to convert 32 bit hex value.
For example user enter number 10, I need to convert this number
Firstly 0x000A (it need to be hex)
And split like this myList = [0x0,0x0,0x0,0xA]
I tried with below command
myNum = 10
value = '0x{0:04X}'.format(myNum)
print(value)
print(list(struct.pack('<H',value)))
I get struct.error: required argument is not an integer
'0x{0:04X}'.format(myNum) value return string so I couldnt split this value correctly.
I expect this value [0x0,0x0,0x0,0xA]
How can I do that ?
You cannot do a strut.pack on a string. It takes integers (as the error describes) and returns a byte string, which you can turn into a list.
import struct
myNum = 10
myHex = '0x{0:04X}'.format(myNum)
print(myHex)
mylist = list(struct.pack('>I',myNum))
print(mylist)
print(list(map(hex, mylist)))
The last line prints them as hex, but they are not integers, they are strings. And you are trying to use little endian in your code, but the expected output is in Big.

Convert Hexadecimal string to long python

I want to get the value of 99997 in big endian which is (2642804992) and then return the answer as a long value
here is my code in python:
v = 99997
ttm = pack('>i', v) # change the integer to big endian form
print ("%x"), {ttm}
r = long(ttm, 16) # convert to long (ERROR)
return r
Output: %x set(['\x00\x01\x86\x9d'])
Error: invalid literal for long() with base 16: '\x00\x01\x86\x9d'
As the string is already in hex form why isn't it converting to a long? How would I remove this error and what is the solution to this problem.
pack will return a string representation of the data you provide.
The string representation is different than a base 16 of a long number. Notice the \x before each number.
Edit:
try this
ttm = pack('>I',v)
final, = unpack('<I',ttm)
print ttm
Notice the use of I, this so the number is treated as an unsigned value
You have to use struct.unpack as a reverse operation to struct.pack.
r, = unpack('<i', ttm)
this will r set to -1652162304.
You just converted the integer value to big endian binary bytes.
This is useful mostly to embed in messages addressed to big-endian machines (PowerPC, M68K,...)
Converting to long like this means parsing the ttm string which should be 0x1869D as ASCII.
(and the print statement does not work either BTW)
If I just follow your question title: "Convert hexadecimal string to long":
just use long("0x1869D",16). No need to serialize it.
(BTW long only works in python 2. In python 3, you would have to use int since all numbers are represented in the long form)
Well, I'm answering to explain why it's bound to fail, but I'll edit my answer when I really know what you want to do.
This is a nice question.
Here is what you are looking for.
s = str(ttm)
for ch in r"\bx'":
s = s.replace(ch, '')
print(int(s, 16))
The problem is that ttm is similar to a string in some aspects. This is what is looks like: b'\x00\x01\x86\x9d'. Supplying it to int (or long) keeps all the non-hex characters. I removed them and then it worked.
After removing the non-hex-digit chars, you are left with 0001869d which is indeed 99997
Comment I tried it on Python 3. But on Python 2 it will be almost the same, you won't have the b attached to the string, but otherwise it's the same thing.

Why does Python remove leading zeroes when converting from string to int?

>>> num = int('0241034812')
>>> print(num)
241034812
>>>
In the above code, I'm setting the variable num to 0241034812; however, when I print the variable it deletes the first zero.
Why is this happening?
Integers are stored/displayed as a "normal" number, not the string value. If you want to display the number prefixed with zeroes you can do that when displaying the variable.
You can use the following syntax to add leading zeros to an integer:
print "%010d" % (241034812,)
The example above will display the integer 241034812 with 10 digits as 0241034812.
I'm setting the variable 'num' to '0241034812'
No, you're setting it to 241,034,812: an integer value, about two hundred forty million. If you want to set it to '0241034812', you should use a string rather than an integer. That is, you should drop the call to int:
>>> num = '0241034812'
>>> print(num)
0241034812
>>>
If you're storing some number in a format where a leading zero would be useful/significant (maybe a barcode, ISBN, or the like), you can re-add them when converting back into a string using .format
>>> num = int('0241034812')
>>> print('{:010d}'.format(num))
0241034812
Briefly, the first 0 in the format spec means to add leading zeros if not present to fill 10 (the 10) characters.
You wanted to print your integer to a specific zero-padded width, use string formatting. The format() function, for example:
>>> num = 241034812
>>> print(format(num, '010d'))
0241034812
or print the original string from which you parsed the integer in the first place.
Integers do not store a 'print width' or any number of leading 0 digits.

Python, string , integer

I have a string variable:
str1 = '0000120000210000'
I want to convert the string into an integer without losing the first 4 zero characters. In other words, I want the integer variable to also store the first 4 zero digits as part of the integer.
I tried the int() function, but I'm not able to retain the first four digits.
You can use two integers, one to store the width of the number, and the other to store the number itself:
kw = len(s)
k = int(s)
To put the number back together in a string, use format:
print '{:0{width}}'.format(k, width=kw) # prints 0000120000210000
But, in general, you should not store identifiers (such as credit card numbers, student IDs, etc.) as integers, even if they appear to be. Numbers in these contexts should only be used if you need to do arithmetic, and you don't usually do arithmetic with identifiers.
What you want simply cannot be done.. Integer value does not store the leading zero's, because there can be any number of them. So, it can't be said how many to store.
But if you want to print it like that, that can be done by formatting output.
EDIT: -
Added #TimPietzcker's comment from OP to make complete answer: -
You should never store a number as an integer unless you're planning on doing arithmetic with it. In all other cases, they should be stored as strings

Categories

Resources