Finding last occurrence of substring in string, replacing that

前端 未结 7 1591
暗喜
暗喜 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:18

    You can use the function below which replaces the first occurrence of the word from right.

    def replace_from_right(text: str, original_text: str, new_text: str) -> str:
        """ Replace first occurrence of original_text by new_text. """
        return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]
    
    0 讨论(0)
  • 2021-01-31 01:18
    a = "A long string with a . in the middle ending with ."
    

    # if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with

    index = a.rfind("with") 
    

    # the result will be 44, as index starts from 0.

    0 讨论(0)
  • 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:]
    
    0 讨论(0)
  • 2021-01-31 01:32

    A one liner would be :

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

    0 讨论(0)
  • 2021-01-31 01:34

    I would use a regex:

    import re
    new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
    
    0 讨论(0)
  • 2021-01-31 01:37

    This should do it

    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:]
    
    0 讨论(0)
提交回复
热议问题