Changing one character in a string

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

    Fastest method?

    There are three ways. For the speed seekers I recommend 'Method 2'

    Method 1

    Given by this answer

    text = 'abcdefg'
    new = list(text)
    new[6] = 'W'
    ''.join(new)
    

    Which is pretty slow compared to 'Method 2'

    timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
    1.0411581993103027
    

    Method 2 (FAST METHOD)

    Given by this answer

    text = 'abcdefg'
    text = text[:1] + 'Z' + text[2:]
    

    Which is much faster:

    timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
    0.34651994705200195
    

    Method 3:

    Byte array:

    timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
    1.0387420654296875
    

提交回复
热议问题