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
3
Answers
This is a Very Simple Problem
What you have to do is just divide the number by 10 and convert it into float with float inbuilt function in python.
now apply it in your problem.
Which version of Python are you using?
int
should convert strings such as'040'
just fine.Are you by any chance typing
int(040)
instead ofint('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.
Use a regex to get a list of 6 string values from your sql data (grouped by 3 digits).
The most efficient way to use the regex is to compile it at the beginning then use the compiled regex on your sql rows.
Use a list-comprehension to obtain a list of floats (converted from strings, also stripping the leading zeros).
Use sequence unpacking to separate into a voltage list and a current list.
You can make a function of that, to easily apply to your sql rows.