'Replace string in var
I am using below code to replace a string, it is actually working, I want to know if there is better way to do it ? I just want to read data coming from serial, if it is same value do nothing but if it is new value print it...
new = ""
old = ""
while True:
new = readQR("/dev/input/event7")
if new != old:
print (new)
old = ""
old = new
new = ""
else:
new = ""
Solution 1:[1]
I am guessing that you are new to Python. In case you already now these then it might help others :)
You can trim down your code to this:
new = ""
old = ""
while True:
new = readQR("/dev/input/event7")
if new != old:
old, new = (new, "") # tuple unpacking
We don't need to do new = "" in else condition as it would be overwritten by readQR in the next iteration.
Brief explanation of old, new = (new, ""):
Here what we are doing is that we are creating a tuple - (new, "") and unpacking it in old and new.
This example might help in understanding the concept of tuple unpacking-
>>> a = 1
>>> b = 2
>>>
>>> t = a, b # t is a tuple
>>> t
(1, 2)
>>>
>>> b, a = t # tuple unpacking - same as b = t[0] and a = t[1]
>>> b
1
>>> a
2
You can refer to this video - Tuples & Tuple Unpacking in Python
Solution 2:[2]
I figured it out based on AnirudhSharma's answer:
old, new = ("", "")
while True:
new = readQR("/dev/input/event7")
if new != old:
old = new
print (new)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | anirudh sharma |
| Solution 2 | Amirhossein Kiani |
