Reputation: 13244
Is there a simpler way to do the following:
def replace(txt,pos,new_char):
return txt[:pos] + new_char + txt[pos+1:]
to do the following?
>>> replace('12345',2,'b')
'12b45'
Upvotes: 3
Views: 100
Reputation: 3695
Just tested some solutions to find the best performance,
The tester source code was:
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
And it's the result:
0.233116149902
0.409259080887
2.64006495476
0.612321138382
0.302225828171
Upvotes: 3
Reputation: 12577
Not sure if this is simpler:
>>> txt = list('12345')
>>> txt[2] = 'b'
>>> ''.join(txt)
'12b45'
Upvotes: 2
Reputation: 142106
Not sure about "better", but an alternative is to adapt something like the following:
>>> ''.join({2: 'b', 4: 'x'}.get(idx, c) for idx, c in enumerate(s))
'12b4x'
Upvotes: 1