【发布时间】:2013-01-07 21:27:18
【问题描述】:
所以我有一长串相同格式的字符串,我想找到最后一个“。”每个字符,并将其替换为“。 - ”。我尝试使用 rfind,但似乎无法正确使用它来执行此操作。
【问题讨论】:
所以我有一长串相同格式的字符串,我想找到最后一个“。”每个字符,并将其替换为“。 - ”。我尝试使用 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 的要求,我认为这应该是此特定功能的默认行为)。根据docs,这个参数是可选的,但是如果给定它必须是一个int。
". -".join("asd.asd.asd.".rsplit(".", 1))。您所做的只是从右侧拆分字符串 1 次,然后使用替换再次连接字符串。
我会使用正则表达式:
import re
new_list = [re.sub(r"\.(?=[^.]*$)", r". - ", s) for s in old_list]
【讨论】:
\.(?=[^.]*$)
一个班轮将是:
str=str[::-1].replace(".",".-",1)[::-1]
【讨论】:
.replace。传递给replace 的两个字符串也必须颠倒过来。否则,当您第二次反转字符串时,您刚刚插入的字母将向后。如果你用一个字母替换一个字母,你只能使用它,即使那样我也不会把它放在你的代码中,以防将来有人必须更改它并开始想知道为什么要写一个单词 sdrawkcab。
您可以使用下面的函数从右边替换第一个出现的单词。
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]
【讨论】:
a = "A long string with a . in the middle ending with ."
#如果你想找到任何字符串最后一次出现的索引,在我们的例子中我们#will找到最后一次出现的索引
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?
'. -'。
replace_right 更好)