You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PyYAML中去除YAML格式里冒号后的多余空格?

解决PyYAML dump时冒号后无空格的需求

当然可以实现!PyYAML默认会在键值对的冒号后添加空格,但我们可以通过自定义Dumper类来覆盖这个默认行为,让输出完全符合你的预期。

具体实现步骤

我们需要重写PyYAML的Dumper类中的write_indicator方法,针对映射节点(也就是字典对应的YAML结构)的冒号,取消后续的空格:

import yaml

class CustomDumper(yaml.Dumper):
    def write_indicator(self, indicator, need_space=True):
        # 仅当是映射节点的键值分隔冒号时,不添加空格
        if indicator == ':' and isinstance(self.current_node, yaml.nodes.MappingNode):
            super().write_indicator(indicator, need_space=False)
        else:
            # 其他场景保持PyYAML默认行为,避免破坏语法
            super().write_indicator(indicator, need_space)

# 你的目标字典
target_dict = {'ab': 8082, 'bc': 8082}

# 使用自定义Dumper生成YAML
result = yaml.dump(target_dict, Dumper=CustomDumper, default_flow_style=False)
print(result)

输出结果

ab:8082
bc:8082

补充说明

  • default_flow_style=False:确保输出是YAML的块样式(每行一个键值对),而不是紧凑的流样式;
  • 自定义方法仅修改映射节点中冒号的输出行为,列表、注释等其他场景的冒号依然保持默认格式,不会破坏YAML语法。

内容的提问来源于stack exchange,提问作者Marcelo BD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:42:31