带边框的python str.replace()

时间:2015-10-08 19:11:31

标签: python string replace

我正在尝试使用函数str.replace(",", ";"[, count]),但是当我填写计数(假设为1)时,它只会更改第一个",",但我想更改某个“,”(使用边界)`有没有人知道如何做到这一点?

2 个答案:

答案 0 :(得分:3)

你可以rsplit加入:

s = "foo,foobar,foo"

print(";".join(s.rsplit(",",1)))

或者反转字符串,再次替换和反转:

print(s[::-1].replace(";",",",1)[::-1])
分裂实际上似乎更快一点:

In [7]: timeit s[::-1].replace(";",",",1)[::-1]
1000000 loops, best of 3: 521 ns per loop

In [8]: timeit ";".join(s.rsplit(",",1))
1000000 loops, best of 3: 416 ns per loop

如果您想更改第i个事件:

def change_ith(st, ith, sep, rep):
    return "".join([s + rep if i == ith else s + sep
                    for i, s in enumerate(st.split(sep, ith), 1)]).rstrip(sep)

输出:

In [15]: s = "foo,foo,bar,foo,foo"

In [16]: change_ith(s, 1, ",",";")
Out[16]: 'foo;foo,bar,foo,foo'

In [17]: change_ith(s, 2, ",",";")
Out[17]: 'foo,foo;bar,foo,foo'

In [18]: change_ith(s, 3, ",",";")
Out[18]: 'foo,foo,bar;foo,foo'

In [19]: change_ith(s, 4, ",",";")
Out[19]: 'foo,foo,bar,foo;foo'

如果你有一个以sep结尾的字符串和一些其他边缘情况,有些情况下join会提供不正确的输出,为了获得更强大的函数,我们需要使用正则表达式传递lambda作为repl arg和使用itertools.count来计算我们获得的匹配数量:

import re
from itertools import count
def change_ith(st, ith, sep, rep):
    return re.sub(sep, lambda m, c=count(1): rep if next(c) == ith else m.group(0), st)

或者应用相同的逻辑加入:

from itertools import count
def change_ith(st, ith, sep, rep):
    cn = count(1)
    return  "".join([rep if ch == sep and next(cn) == ith else ch 
                   for ch in st])

答案 1 :(得分:0)

你应该再次反转,替换和反转。我在下面的例子中使用反向索引:

s = "one, two, three, four, five"

print str.replace(s[::-1], ',', ';', 1)[::-1]
相关问题