Changing one character in a string

前端 未结 11 1031
抹茶落季
抹茶落季 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:01

    Python strings are immutable, you change them by making a copy.
    The easiest way to do what you want is probably:

    text = "Z" + text[1:]
    

    The text[1:] returns the string in text from position 1 to the end, positions count from 0 so '1' is the second character.

    edit: You can use the same string slicing technique for any part of the string

    text = text[:1] + "Z" + text[2:]
    

    Or if the letter only appears once you can use the search and replace technique suggested below

提交回复
热议问题