Changing one character in a string

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

    I would like to add another way of changing a character in a string.

    >>> text = '~~~~~~~~~~~'
    >>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
    '~+~~~~~~~~~'
    

    How faster it is when compared to turning the string into list and replacing the ith value then joining again?.

    List approach

    >>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
    0.8268570480013295
    

    My solution

    >>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
    0.588400217000526
    

提交回复
热议问题