我有一个以相同格式排列的字符串列表,我想在每个字符串中找到最后一个“.”字符,并将其替换为“. - ”。我尝试使用rfind来实现这个目标,但我似乎无法正确利用它。
这样就可以了
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:]
从右侧进行替换:
def replace_right(source, target, replacement, replacements=None):
return replacement.join(source.rsplit(target, replacements))
使用中:
>>> replace_right("asd.asd.asd.", ".", ". -", 1)
'asd.asd.asd. -'
replacements=None
参数似乎对我来说是一个错误,因为如果省略该参数,函数将会报错(在Python 2.7中尝试过)。我建议要么删除默认值,将其设置为-1(表示无限替换),或者更好的方法是将其设置为replacements=1
(我认为这应该是根据OP的要求此特定函数的默认行为)。根据文档所述,此参数是可选的,但如果给出,则必须是int类型。 - remarkov". -".join("asd.asd.asd.".rsplit(".", 1))
。你所做的就是从字符串右侧进行一次分割,并使用替换将字符串重新连接起来。 - bsplosion我会使用正则表达式:
import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
\.(?=[^.]*$)
- georgstr=str[::-1].replace(".",".-",1)[::-1]
这行代码可以将字符串中第一个点替换为“.-”,并反转字符串。.replace
。传递给replace
的两个字符串也必须被反转。否则,当你第二次反转字符串时,刚刚插入的字母将会颠倒过来。只有在替换一个字母为另一个字母的情况下才可以使用这种方法,即便如此,我也不会将其放入你的代码中,以防将来有人需要进行更改,并开始疑惑为什么一个单词被写成了sdrawkcab。 - user3064538def 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]
a = "A long string with a . in the middle ending with ."
# 如果你想找到任何字符串的最后一次出现的索引,在我们的例子中,我们将找到 with 的最后一次出现的索引
index = a.rfind("with")
# 结果将是44,因为索引从0开始。
朴素的方法:
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:]
a
吗? - Alex L'. -'
反转输出。 - Gareth Lattyreplace_right
更好) - Alex L