Finding last occurrence of substring in string, re

2020-05-15 07:38发布

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 seem to utilize it properly to do this.

7条回答
▲ chillily
2楼-- · 2020-05-15 07:57

I would use a regex:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
查看更多
啃猪蹄的小仙女
3楼-- · 2020-05-15 08:05

To replace from the right:

def replace_right(source, target, replacement, replacements=None):
    return replacement.join(source.rsplit(target, replacements))

In use:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
查看更多
等我变得足够好
4楼-- · 2020-05-15 08:05

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]
查看更多
叛逆
5楼-- · 2020-05-15 08:08

A one liner would be :

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

查看更多
来,给爷笑一个
6楼-- · 2020-05-15 08:11

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:]
查看更多
姐就是有狂的资本
7楼-- · 2020-05-15 08:14

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:]
查看更多
登录 后发表回答