我正在尝试使用函数 str.replace(",", ";"[, count])
但当我填写 count (假设 1)时,它只会更改第一个","
但我想更改某个“,”(使用边界)`有人知道如何做到这一点吗?
最佳答案
您可以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])
关于带边框的 python str.replace(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33024080/