查找字符串中最后一次出现的子字符串,替换它

Ada*_*yar 100 python string parsing

所以我有一长串相同格式的字符串,我想找到最后一个"." 每个字符中的字符,并用". - "替换它.我尝试过使用rfind,但我似乎无法正确使用它来做到这一点.

Adi*_*hag 156

这应该做到这一点

old_string = "this is going to have a full stop. some written sstuff!"
k = old_string.rfind(".")
new_string = old_string[:k] + ". - " + old_string[k+1:]
Run Code Online (Sandbox Code Playgroud)


Var*_*ngh 26

要从右边取代:

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))
Run Code Online (Sandbox Code Playgroud)

正在使用:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
Run Code Online (Sandbox Code Playgroud)


Tim*_*ker 14

我会使用正则表达式:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
Run Code Online (Sandbox Code Playgroud)

  • 如果根本没有点,这是唯一有效的答案.我虽然使用了前瞻:`\.(?= [^.]*$)` (2认同)

maz*_*azs 6

一个班轮将是:

str=str[::-1].replace(".",".-",1)[::-1]