Changing one character in a string

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

    Strings are immutable in Python, which means you cannot change the existing string. But if you want to change any character in it, you could create a new string out it as follows,

    def replace(s, position, character):
        return s[:position] + character + s[position+1:]
    

    replace('King', 1, 'o')
    // result: Kong

    Note: If you give the position value greater than the length of the string, it will append the character at the end.

    replace('Dog', 10, 's')
    // result: Dogs

提交回复
热议问题