1

I am storing the result of a string in a variable and would like to know how to check if the string contains specific characters. I understand that the 'in' command can be used to check if a character/s is contained in a string "some string". My issue is I can't do this when the character/s are being evaluated against a variable.

Example:

s = ser.read(1000) 
if "developer" in s:
  print("True")
else:
  print("False")

I'm getting an error

a bytes-like object is required, not 'str'

Could someone help with this?

Thanks.

Derlin
  • 9,572
  • 2
  • 32
  • 53
SamL
  • 133
  • 2
  • 3
  • 16
  • 4
    You are reading a stream (a file, I suppose, or maybe a socket) as bytes (e.g. with mode `'rb'` for a file). Either read it in text mode (e.g. `'r'`) or use a byte array in your conditional instead of a string, e.g. `if b"developer" in s:`. – jdehesa Mar 25 '19 at 16:50
  • Not really - OP is enquiring about *matching*, not writing – PrinceOfCreation Mar 25 '19 at 16:52
  • Thanks a lot for that. Works well now! – SamL Mar 25 '19 at 16:54

1 Answers1

3

if you've done something like

ser = open("hello.txt", "rb")
s = ser.read(1000) 
if "developer" in s:
  print("True")
else:
  print("False")
ser.close()

Just change 'rb' in 'r' (or do not put anything, it will be 'r' as default). A better way to open a file is this

with open("hello.txt", "r", encoding='utf-8') as ser:
    s = ser.read(1000) 
    if "developer" in s:
        print("True")
    else:
        print("False")
PythonProgrammi
  • 22,305
  • 3
  • 41
  • 34