我試圖簡單地用另一個專案替換一個串列專案,除了新專案中有一個空格。當它替換時,當我只想要一個時,它會創建兩個串列項。我怎樣才能讓它只是串列中的一項?
這是一個最小的可重現示例:
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但我需要串列項中有一個空格。這可能很簡單,但我無法理解。謝謝你。
uj5u.com熱心網友回復:
您可以迭代sorted_fm_becmg以單獨替換每個字串:
sorted_fm_becmg = [b.replace(line_to_print, new_becmg) for b in sorted_fm_becmg]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339434.html
