Python str.format处理含冒号字典键报错,求替代方案
问题解决:带冒号的字典键在字符串格式化中的替换方案
你的问题核心是str.format()会把键中的冒号误判为格式说明符的分隔符,导致无法正确匹配带冒号的字典键。下面提供三种可行的解决思路:
方案1:使用string.Template(推荐)
string.Template的变量语法不会解析冒号,适合处理带特殊字符的键。只需将格式串中的{key}替换为${key},再调用substitute方法即可:
from typing import Any, Dict from string import Template if __name__ == '__main__': dict_of_actions = {'ga:userType': 'New Visitor', 'ga:source': 'source', 'ga:adContent': 'random_hash1', 'ga:eventLabel': 'company_added', 'ga:dateHourMinute': '202305181019', 'ga:users': '1'} # 格式串改用${键名}的形式 string_with_path = '${ga:adContent}_${ga:dateHourMinute}' def _get_node_value_by_template( action: Dict, template_string: str ) -> Any: try: return Template(template_string).substitute(**action) except (KeyError, TypeError) as e: raise Exception(e) result = _get_node_value_by_template(dict_of_actions, string_with_path) print(result) # 输出:random_hash1_202305181019
方案2:自定义正则替换逻辑
通过正则表达式匹配所有{}包裹的键名,手动从字典中取值替换,完全控制解析逻辑:
from typing import Any, Dict import re if __name__ == '__main__': dict_of_actions = {'ga:userType': 'New Visitor', 'ga:source': 'source', 'ga:adContent': 'random_hash1', 'ga:eventLabel': 'company_added', 'ga:dateHourMinute': '202305181019', 'ga:users': '1'} string_with_path = '{ga:adContent}_{ga:dateHourMinute}' def _get_node_value_by_regex( action: Dict, format_string: str ) -> Any: try: # 匹配所有{键名}的模式 pattern = re.compile(r'\{([^}]+)\}') # 逐个替换匹配到的键 return pattern.sub(lambda match: action[match.group(1)], format_string) except (KeyError, TypeError) as e: raise Exception(e) result = _get_node_value_by_regex(dict_of_actions, string_with_path) print(result) # 输出:random_hash1_202305181019
方案3:修改格式串适配str.format_map
如果想继续使用str.format系列方法,可以将格式串改为{[键名]}的形式,再用format_map方法(支持通过键名索引取值):
from typing import Any, Dict if __name__ == '__main__': dict_of_actions = {'ga:userType': 'New Visitor', 'ga:source': 'source', 'ga:adContent': 'random_hash1', 'ga:eventLabel': 'company_added', 'ga:dateHourMinute': '202305181019', 'ga:users': '1'} # 格式串改为{[键名]}的形式 string_with_path = '{[ga:adContent]}_{[ga:dateHourMinute]}' def _get_node_value_by_format_map( action: Dict, format_string: str ) -> Any: try: return format_string.format_map(action) except (KeyError, TypeError, IndexError) as e: raise Exception(e) result = _get_node_value_by_format_map(dict_of_actions, string_with_path) print(result) # 输出:random_hash1_202305181019
内容的提问来源于stack exchange,提问作者Jack
相关产品推荐
相关产品推荐

