107

したがって、同じ形式の文字列の長いリストがあり、最後の「。」を見つけたいと思います。それぞれの文字を ". - " に置き換えます。rfind を使用してみましたが、これを適切に利用できないようです。

4

7 に答える 7

168

これでできるはず

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:]
于 2013-01-24T07:35:09.320 に答える
28

右から置換するには:

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

使用中で:

>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
于 2013-01-24T07:39:01.400 に答える
15

私は正規表現を使用します:

import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
于 2013-01-24T07:34:37.407 に答える
6

ワンライナーは次のようになります。

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

于 2016-03-07T12:48:23.720 に答える
-1

単純なアプローチ:

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の答えrfind

pos = a.rfind('.')
a[:pos] + '. -' + a[pos+1:]
于 2013-01-24T07:38:13.433 に答える