Skip to main content
 首页 » 编程设计

python之格式化原始字符串 Python

2025年05月04日21Terrylee

我在 Python 中有一个原始字符串,它是通过 imap 库检索的。

看起来像这样:

Season: Winter 2017-18 
Activity: Basketball - Boys JV 
*DATE: 02/13/2018 * - ( previously 02/06/2018 ) 
Event type: Game 
Home/Host: Clear Lake 
Opponent: Webster City 
*START TIME: 6:15PM CST* - ( previously 4:30PM CST ) 
Location: Clear Lake High School, 125 N. 20th Street, Clear Lake, IA 

废弃每个标签后的数据的最佳方法是什么(标签是DATE:)例如DATE:02/13/2018 * -(以前是02/06/2018 ) 将设置为等于 Date 之类的变量,因此当打印 print(date) 时,02/13/2018 * - (以前是 02/06/2018 ) 将是输出。

我尝试了下面的代码,但它每行打印一个字符。谢谢!

for line in message: 
     if "DATE:" in line: 
          print line 

请您参考如下方法:

您可以使用正则表达式和字典:

import re 
s = """ 
Season: Winter 2017-18 
Activity: Basketball - Boys JV 
*DATE: 02/13/2018 * - ( previously 02/06/2018 ) 
Event type: Game 
Home/Host: Clear Lake 
Opponent: Webster City 
*START TIME: 6:15PM CST* - ( previously 4:30PM CST ) 
Location: Clear Lake High School, 125 N. 20th Street, Clear Lake, IA 
""" 
final_dict = {(a[1:] if a.startswith('*') else a).strip('\r'):b.strip('\r') for a, b in filter(lambda x:len(x)> 1, [re.split('\:\s', i) for i in filter(None, s.split('\n'))])} 

输出:

{'Home/Host': 'Clear Lake', 'Season': 'Winter 2017-18', 'START TIME': '6:15PM CST* - ( previously 4:30PM CST )', 'Location': 'Clear Lake High School, 125 N. 20th Street, Clear Lake, IA', 'Activity': 'Basketball - Boys JV', 'DATE': '02/13/2018 * - ( previously 02/06/2018 )', 'Event type': 'Game', 'Opponent': 'Webster City'}