views:

100

answers:

3

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 !

+4  A: 

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'
bobince
+1  A: 

I would use string.replace():

>>> import string
>>> az = string.lowercase
>>> az = az.replace('rs', '11')
>>> az
'abcdefghijklmnopq11tuvwxyz'
hughdbrown
A: 

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
Catalin Festila