开发者

change 2 byte in a string

I'd like to change 2 byte in a string like t开发者_开发问答his:

"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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜