Finding last occurrence of substring in string, replacing that

前端 未结 7 1667
暗喜
暗喜 2021-01-31 01:07

So I have a long list of strings in the same format, and I want to find the last \".\" character in each one, and replace it with \". - \". I\'ve tried using rfind, but I can\'t

7条回答
  •  耶瑟儿~
    2021-01-31 01:24

    Naïve approach:

    a = "A long string with a . in the middle ending with ."
    fchar = '.'
    rchar = '. -'
    a[::-1].replace(fchar, rchar[::-1], 1)[::-1]
    
    Out[2]: 'A long string with a . in the middle ending with . -'
    

    Aditya Sihag's answer with a single rfind:

    pos = a.rfind('.')
    a[:pos] + '. -' + a[pos+1:]
    

提交回复
热议问题