Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if statement string match
#3
(Sep-04-2021, 05:39 PM)deanhystad Wrote: You should test "==" not "is". Is should only be used when you are testing if two objects are the same instance. Below I make two bytes. They are constructed of the same bytes, but they are different objects.
x = bytes('12345', 'utf-8')
y = bytes('12345', 'utf-8')
print(x, y, id(x), id(y), x is y, x == y)
Output:
b'12345' b'12345' 2409442857008 2409442857104 False True
x and y are equivalent, but they are not the same. x is y returns False and x == y returns True.
Just in case rfm9x.receive() returns str, the same is true for them.
x = ''.join(['a', 'b', 'c'])
y = ''.join(['a', 'b', 'c'])
print(x, y, id(x), id(y), x is y, x == y)
Output:
abc abc 3078969735600 3078969723888 False True
You may wonder why I constructed the strings as I did. The reason for using join instead of a string literal is Python is clever and tries to be efficient. This code does not create two str objects.
x = 'abc'
y = 'abc'
print(x, y, id(x), id(y), x is y, x == y)
Output:
abc abc 1811113886448 1811113886448 True True
In this example not only does x == y, but x is y. Notice that the object id for x and y are the same.

thanks for the == tip
this worked for me...

onset = bytes("onset", "utf-8")
unset = bytes("unset", "utf-8")

while True:
    packet = rfm9x.receive(timeout=5)
    
    if packet is None:
        led.value = False
        print("Received nothing! Listening again...")
    elif packet == onset:
            print("its on")
    elif packet == unset:
            print("its off")
    else:
        led.value = True
        print("Received (raw bytes): {0}".format(packet))
        packet = str(packet, "ascii")
Reply


Messages In This Thread
if statement string match - by javiopro - Sep-04-2021, 04:37 PM
RE: if statement string match - by deanhystad - Sep-04-2021, 05:39 PM
RE: if statement string match - by javiopro - Sep-04-2021, 05:56 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Trying to compare string values in an if statement israelsattleen 1 1,149 Jul-08-2023, 03:49 PM
Last Post: deanhystad
  String concatenation in SQL update statement hammer 3 2,566 Feb-24-2022, 08:00 PM
Last Post: hammer
  string match Kristenl2784 1 1,884 Jul-28-2020, 03:14 PM
Last Post: Kristenl2784
  regex match in a string batchen 4 4,340 Jan-20-2020, 08:48 AM
Last Post: batchen
  SyntaxError: EOL while scanning string literal on with open() statement Regulus 3 8,350 Feb-23-2018, 06:40 PM
Last Post: nilamo
  How to do String match SriRajesh 2 4,243 Apr-02-2017, 01:31 PM
Last Post: zivoni

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020