Changing one character in a string

前端 未结 11 958
抹茶落季
抹茶落季 2020-11-22 03:21

What is the easiest way in Python to replace a character in a string?

For example:

text = \"abcdefg\";
text[1] = \"Z\";
           ^
11条回答
  •  野性不改
    2020-11-22 04:02

    Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings):

    s = "abcdefg"
    b_s = bytearray(s)
    b_s[1] = "Z"
    s = str(b_s)
    print s
    aZcdefg
    

    edit: Changed str to s

    edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with unicode.

提交回复
热议问题