替换单个字符的其他方法

时间:2013-04-03 17:08:09

标签: python python-3.x

是否有更简单的方法来执行以下操作:

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

要做到以下几点?

>>> replace('12345',2,'b')
'12b45'

3 个答案:

答案 0 :(得分:3)

刚刚测试了一些解决方案,以找到最佳性能,

测试人员的源代码是:

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

答案 1 :(得分:2)

不确定这是否更简单:

>>> txt = list('12345')
>>> txt[2] = 'b'
>>> ''.join(txt)
'12b45'

答案 2 :(得分:1)

不确定“更好”,但另一种选择是适应以下内容:

>>> ''.join({2: 'b', 4: 'x'}.get(idx, c) for idx, c in enumerate(s))
'12b4x'