0

I have a list, say named mac, which saves 6-bytes mac address. I want to set the last byte to 0, then I use:

mac[5] = 0

But it gives me error:

TypeError: 'str' object does not support item assignment

How to fix this error?

TieDad
  • 9,143
  • 5
  • 32
  • 58

1 Answers1

7

because mac is a str and strings are immutable in python.

mac = list(mac)
mac[5] = '0'
mac = ''.join(mac) #to get mac in str

or use bytearray, which could function as a mutable string.

>>> x = bytearray('abcdef')
>>> x
bytearray(b'abcdef')
>>> x[5] = '0'
>>> x
bytearray(b'abcde0')
>>> str(x)
'abcde0'
thkang
  • 11,215
  • 14
  • 67
  • 83