如何用其中包含 space 的字符串替换列表中的项目?

How can I replace an item in a list with a string that has a space in it?

我正在尝试用另一个项目简单地替换一个列表项目,除了新项目中有一个 space。当它替换时,它会创建两个列表项,而我只需要一个。我怎样才能让它成为列表中的一项?

这是一个最小的可重现示例:

import re

cont = "BECMG 2622/2700 32010KT CAVOK"
actual = "BECMG 2622"
sorted_fm_becmg = ['BECMG 262200', '272100']
line_to_print = 'BECMG 262200'

becmg = re.search(r'%s[/]\d\d\d\d' % re.escape(actual), cont).group()
new_becmg = "BECMG " + becmg[-4:] + "00" # i need to make this one list item when it replaces 'line_to_print'
sorted_fm_becmg = (' '.join(sorted_fm_becmg).replace(line_to_print, new_becmg)).split()

print(sorted_fm_becmg)

我需要 sorted_fm_becmg 看起来像这样:['BECMG 270000', '272100']

我尝试将 new_becmg 设为列表项,我尝试删除 new_becmg 中字符串中的 space 但我需要列表项具有 space 在里面。 这可能很简单,但我无法理解。谢谢。

您可以遍历 sorted_fm_becmg 来单独替换每个字符串:

sorted_fm_becmg = [b.replace(line_to_print, new_becmg) for b in sorted_fm_becmg]