3

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

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

执行以下操作?

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

3 回答 3

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
于 2013-04-03T17:10:12.223 回答
2

不确定这是否更简单:

>>> txt = list('12345')
>>> txt[2] = 'b'
>>> ''.join(txt)
'12b45'
于 2013-04-03T17:21:50.763 回答
1

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

>>> ''.join({2: 'b', 4: 'x'}.get(idx, c) for idx, c in enumerate(s))
'12b4x'
于 2013-04-03T17:20:59.680 回答