Hi All,
I'd like to change 2 byte in a string like this:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Let's imagine I want to replace 'RS'
by 11, I know how to do it with one byte like [:], but for 2 or more in the middle of the string ?
Thanks !
Hi All,
I'd like to change 2 byte in a string like this:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Let's imagine I want to replace 'RS'
by 11, I know how to do it with one byte like [:], but for 2 or more in the middle of the string ?
Thanks !
Strings are immutable, you can't change them. You have to make a new string from parts of the old one:
>>> az= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> az= az[:17]+'11'+az[19:]
>>> az
'ABCDEFGHIJKLMNOPQ11TUVWXYZ'
although depending one what you're doing there may be a more appropriate way of handling it than relying on fixed indices, eg.
>>> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.replace('RS', '11', 1)
'ABCDEFGHIJKLMNOPQ11TUVWXYZ'
I would use string.replace():
>>> import string
>>> az = string.lowercase
>>> az = az.replace('rs', '11')
>>> az
'abcdefghijklmnopq11tuvwxyz'
I think it's a trick question, see "how to do it with one byte":
>>> st="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
>>> st="ABCDEFGHIJKLMNOPQRSTUVWXYZ".replace("R","1").replace("S","1")
>>> print st
ABCDEFGHIJKLMNOPQ11TUVWXYZ