+-
python – 替换单个字符的其他方法
是否有更简单的方法来执行以下操作:

def replace(txt,pos,new_char):
    return txt[:pos] + new_char + txt[pos+1:]

做以下事情?

>>> replace('12345',2,'b')
'12b45'
最佳答案
刚刚测试了一些解决方案以找到最佳性能,

测试人员的源代码是:

import __main__
from itertools import permutations
from time import time

def replace1(txt, pos, new_char):
    return txt[:pos] + new_char + txt[pos+1:]

def replace2(txt, pos, new_char):
    return '{0}{1}{2}'.format(txt[:pos], new_char, txt[pos+1:])

def replace3(txt, pos, new_char):
    return ''.join({pos: new_char}.get(idx, c) for idx, c in enumerate(txt))

def replace4(txt, pos, new_char):    
    txt = list('12345')
    txt[pos] = new_char
    ''.join(txt)

def replace5(txt, pos, new_char):
    return '%s%s%s' % (txt[:pos], new_char, txt[pos+1:])


words = [''.join(x) for x in permutations('abcdefgij')]

for i in range(1, 6):
    func = getattr(__main__, 'replace{}'.format(i))

    start = time()
    for word in words:
        result = func(word, 2, 'X')
    print time() - start

这是结果:

0.233116149902
0.409259080887
2.64006495476
0.612321138382
0.302225828171
点击查看更多相关文章

转载注明原文:python – 替换单个字符的其他方法 - 乐贴网