简体   繁体   English

如何从列表Python中的项目组成的整数中获取前导零

[英]how to get Leading Zeros in integer composed from items on a list Python

I am trying to create a six digit number constructed from serval modbus registers. 我正在尝试创建一个由serval modbus寄存器构造的六位数字。 I have no idea how modbus register work but was able to map certain numbers to decimal values. 我不知道modbus寄存器如何工作,但能够将某些数字映射到十进制值。

Example : 示例

'12336': '00', 
'12592': '01', 
'12848': '02', 
'13104': '03',
.
.
.
'14649': '99'

I created a dictionary holding the full list of number from 00 to 99, I start reading 3 holdng registers and iterate over them and create an empty list that gets populated with the value corresponding to the key : value pair in the dictionary then I join them and cast to integer hoping to get the 6 digit number. 我创建了一个字典,其中包含从00到99的完整数字列表,我开始阅读3个holdng寄存器并迭代它们并创建一个空列表,该列表将填充对应于字典中的键:值对的值然后我加入它们并转换为整数,希望得到6位数字。 It kind of works only if i have no leading zeros on my number, however if i do get leading zeros my number gets cut down to where that significant number start. 它只有在我的号码上没有前导零时才有效,但如果我确实得到前导零,那么我的号码会减少到那个有效数字开始的位置。

My code : 我的代码

NUMBERS  = {
    '12336': '00', '12592': '01', '12848': '02', '13104': '03', '13360': '04', '13616': '05', '13872': '06', '14128': '07', '14384': '08', '14640': '09', '12337': '10',

    }




def scanned_code():
    code = client.read_holding_registers(1, 3, unit=0)
    r = code.registers
    print(r)
    value = []

    for i in r :
        value.append(NUMBERS[str(i)])
    return value

def numb(lista):
    print(lista)
    res = int("".join(map(str, lista)))
    return res



scan_job = numb(scanned_code())
print(scan_job)

Let's say I have 3 holding registers with the following values: 12336, 13360, 14128 I would spect to generate this number 000407 . 假设我有3个保持寄存器,其值如下: 12336,13360,14128我想生成这个数字000407 instead I get 407 相反,我得到407

Actual values it get in terminal when executing script 执行脚本时在终端中获得的实际值

[12592, 13360, 14128]
['01', '04', '07']
10407

[12336, 13360, 14128]
['00', '04', '07']
407

In Python (and pretty much any other programming language), numbers are stored as binary integers. 在Python(以及几乎任何其他编程语言)中,数字存储为二进制整数。 So the concept of "leading zeroes" is meaningless: to the computer, 123 and 000123 would be stored exactly the same. 因此,“前导零”的概念毫无意义:对于计算机, 123000123将完全相同地存储。 (And, indeed, a mathematician would say those represent exactly the same value.) (事实上​​,数学家会说那些代表完全相同的值。)

If you want leading zeroes, you should store the value as a string. 如果需要前导零,则应将值存储为字符串。 Just remove the int call within your numb function. 只需删除numb功能中的int调用即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM