Changing one character in a string

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

    Like other people have said, generally Python strings are supposed to be immutable.

    However, if you are using CPython, the implementation at python.org, it is possible to use ctypes to modify the string structure in memory.

    Here is an example where I use the technique to clear a string.

    Mark data as sensitive in python

    I mention this for the sake of completeness, and this should be your last resort as it is hackish.

提交回复
热议问题