Search code examples
pythonmysqlsyntax-error

How to convert a three digit integer (xxx) with a 1 decimal place float (xx.x)?


Currently I'm getting data from some sensors with voltage(V) and current(C) values which is decoded into text as V040038038039C125067 to be stored in MYSQL DB table. The voltage contains 4 different voltage values combined while the current contains 2 different current values combined where each value represented by 3 digits in the format of Voltage xx.x C: Current xx.x. For example, the current value of C125067 is actually 12.5 and 06.7A respectively. I tried to use python slicing some and some simple math to achieve this by dividing the values by 10 e.g. C125067 = 125/10 = 12.5. While this works for integers with first non-zero values (e.g. 125), when I tried to perform the same for values such as 040 or 067, I get the SyntaxError: leading zeros in decimal integer literals are not permitted error. Are there any better ways to achieve the desired decoding output of xx.x or to insert a decimal point before the last digit etc? Thanks.

v1 = voltage[1:4]
v2 = voltage[4:7]
v3 = voltage[7:10]
v4 = voltage[10:13]
c1 = current[1:4]
c2 = current[4:7]

volt_1 = int(v1)/10
volt_2 = int(v2)/10
volt_3 = int(v3)/10
volt_4 = int(v4)/10

curr_1 = int(c1)/10
curr_2 = int(c2)/10

Solution

  • Which version of Python are you using? int should convert strings such as '040' just fine.

    Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 16:56:21) 
    Type 'copyright', 'credits' or 'license' for more information
    IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help.
    
    In [1]: int('040')
    Out[1]: 40
    
    In [2]: 
    

    Are you by any chance typing int(040) instead of int('040')? One is a decimal integer literal while the latter is a string.

    Leading zeros are not allowed in Python?

    Using python 3.9.13, your code works without problems.

    voltage = "V040038038039C125067"
    
    v1 = voltage[1:4]
    v2 = voltage[4:7]
    v3 = voltage[7:10]
    v4 = voltage[10:13]
    
    volt_1 = int(v1)/10
    volt_2 = int(v2)/10
    volt_3 = int(v3)/10
    volt_4 = int(v4)/10
    
    print(v1, v2, v3, v4, volt_1, volt_2, volt_3, volt_4)
    # 040 038 038 039 4.0 3.8 3.8 3.9