有沒有一種簡單的方法來做到以下幾點:其他方式來替代單個字符
def replace(txt,pos,new_char):
return txt[:pos] + new_char + txt[pos+1:]
做到以下幾點?
>>> replace('12345',2,'b')
'12b45'
有沒有一種簡單的方法來做到以下幾點:其他方式來替代單個字符
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
小心備份一些測量? –
@PavelAnossov我想它會創建一個新的字符串而不是兩個,不是? – MostafaR
不,它會創建格式字符串,兩個切片和結果。 OP的替換創建了兩個片段,這是一個臨時的串聯結果,結果是四個。 –
不確定「更好「,但另一種方法是調整如下內容:
>>> ''.join({2: 'b', 4: 'x'}.get(idx, c) for idx, c in enumerate(s))
'12b4x'
不知道這是簡單的:
>>> txt = list('12345')
>>> txt[2] = 'b'
>>> ''.join(txt)
'12b45'
爲什麼不能使用替代? – Harpal
在一般情況下,我想不出任何更好的辦法。你想要達到什麼目的? –
請注意,如果您正在寫入文件,您最好的選擇可能不是創建新字符串,而是將這些部分單獨傳遞給'your_file.write(piece)'。 –