优雅地迭代字符串替换

gzz*_*zzo 3 python

说我有一个看起来像的字符串

'one, two, three,'
Run Code Online (Sandbox Code Playgroud)

什么是pythonic方式迭代替换',''.' 一次一个?理想情况下,函数的返回值如下所示:

['one. two, three,' , 'one, two. three,' , 'one, two, three.']
Run Code Online (Sandbox Code Playgroud)

选择答案的推理,感谢您的贡献!

import timeit

def one(s):
    b = ["%s.%s" % (s[:i], s[i+1:]) for i, c in enumerate(s) if c == ","]

def two(s):
    b = [s[:i] + "." + s[i+1:] for i in range(len(s)) if s[i] == ","]

def thr(s):
    b = [s[:i] + "." + s[i+1:] for i, c in enumerate(s) if s[i] == ","]

def fou(s):
    ss = s.split(',')
    b = [','.join(ss[:i]) + '.' + ','.join(ss[i:]) for i in range(1,len(ss))]

a = 'one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,'

print(timeit.timeit('one(a)', 'from __main__ import one, a', number = 1000000))
print(timeit.timeit('two(a)', 'from __main__ import two, a', number = 1000000))
print(timeit.timeit('thr(a)', 'from __main__ import thr, a', number = 1000000))
print(timeit.timeit('fou(a)', 'from __main__ import fou, a', number = 1000000))

#   C:\dev\goddangit>python timin.py
#   14.3008527857
#   11.8759967856
#   13.3739626708
#   18.8536401851
Run Code Online (Sandbox Code Playgroud)

tob*_*s_k 5

单行,s'one, two, three,':

>>> [s[:i] + "." + s[i+1:] for i in range(len(s)) if s[i] == ","]
['one. two, three,', 'one, two. three,', 'one, two, three.']
Run Code Online (Sandbox Code Playgroud)

或者,将最外面[ ]的替换为替换( )为生成器对象.

当然,这仅适用于单字符替换.更一般地,用其他字符串替换子字符串,您应该使用其他解决方案之一,例如,使用正则表达式.