要保留原始空格的替换单词,可以使用正则表达式来匹配单词并替换。以下是一个示例代码:
import re
def replace_words_with_spaces(input_string, word_to_replace, replacement_word):
# 使用正则表达式匹配单词,并保留原始空格
pattern = r'\b(' + re.escape(word_to_replace) + r')\b'
output_string = re.sub(pattern, replacement_word, input_string)
return output_string
# 示例用法
input_string = "This is a sample sentence with multiple words."
word_to_replace = "sample"
replacement_word = "example"
output_string = replace_words_with_spaces(input_string, word_to_replace, replacement_word)
print(output_string)
输出:
This is a example sentence with multiple words.
这个示例中,replace_words_with_spaces
函数使用了 re.sub
方法来替换字符串中的单词。首先,我们使用 re.escape
函数对要替换的单词进行转义,以避免其中包含的特殊字符影响正则表达式的匹配。然后,我们使用 \b
来限定单词的边界。这样可以确保只匹配整个单词,而不会匹配到单词的一部分。最后,我们使用替换词替换匹配到的单词。
需要注意的是,这个示例中只能替换单词本身,并不能保留原始单词中的其他空格。如果想要保留原始单词中的空格,可以使用更复杂的正则表达式模式来匹配单词及其前后的空格。这里的示例代码只是一个简单的示例,你可以根据具体需求进行修改。
下一篇:保留原始列名