1# literals 2print(b'123') 3print(br'123') 4print(rb'123') 5print(b'\u1234') 6 7# construction 8print(bytes()) 9print(bytes(b'abc')) 10 11# make sure empty bytes is converted correctly 12print(str(bytes(), 'utf-8')) 13 14a = b"123" 15print(a) 16print(str(a)) 17print(repr(a)) 18print(a[0], a[2]) 19print(a[-1]) 20print(str(a, "utf-8")) 21print(str(a, "utf-8", "ignore")) 22try: 23 str(a, "utf-8", "ignore", "toomuch") 24except TypeError: 25 print("TypeError") 26 27s = 0 28for i in a: 29 s += i 30print(s) 31 32 33print(bytes("abc", "utf-8")) 34print(bytes("abc", "utf-8", "replace")) 35try: 36 bytes("abc") 37except TypeError: 38 print("TypeError") 39try: 40 bytes("abc", "utf-8", "replace", "toomuch") 41except TypeError: 42 print("TypeError") 43 44print(bytes(3)) 45 46print(bytes([3, 2, 1])) 47print(bytes(range(5))) 48 49# Make sure bytes are not mistreated as unicode 50x = b"\xff\x8e\xfe}\xfd\x7f" 51print(len(x)) 52print(x[0], x[1], x[2], x[3]) 53 54# Make sure init values are not mistreated as unicode chars 55# For sequence of known len 56print(bytes([128, 255])) 57# For sequence of unknown len 58print(bytes(iter([128, 255]))) 59 60# Shouldn't be able to make bytes with negative length 61try: 62 bytes(-1) 63except ValueError: 64 print('ValueError') 65