English 简体中文 繁體中文 한국 사람 日本語 Deutsch русский بالعربية TÜRKÇE português คนไทย french
查看: 3|回复: 0

yaml多行文本的写法和区别

[复制链接]
查看: 3|回复: 0

yaml多行文本的写法和区别

[复制链接]
查看: 3|回复: 0

220

主题

0

回帖

670

积分

高级会员

积分
670
GsiqgUuR

220

主题

0

回帖

670

积分

高级会员

积分
670
2025-2-21 20:01:01 | 显示全部楼层 |阅读模式
直接看效果(pip install pyyaml):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import yaml

yaml_data = """
example1: |
  This is line one.
  This is line two.
example2: |-
  This is line one.
  This is line two.
example3: >-
  This is line one.
  This is line two.
"""

# 将 YAML 数据解析为 Python 对象
data = yaml.safe_load(yaml_data)

# 访问特定字段
print(f"example1: {data['example1']}")
print(f"example2: {data['example2']}")
print(f"example3: {data['example3']}")
输出结果:
1
2
3
4
5
6
example1: This is line one.
This is line two.

example2: This is line one.
This is line two.
example3: This is line one. This is line two.
结论

在 YAML 中,|、|- 和 >- 都用于定义多行字符串,但它们的处理方式不同:

  • |

    • 保留换行符。
    • 生成的字符串在每行的末尾保留换行符。

  • |-

    • 类似于 |,但去掉最后的换行符。
    • 结果中的最后一行不会有换行符。

  • >-

    • 将换行符转换为空格。
    • 结果中的所有行会被连接成一行,中间用空格分隔,最后一行也没有换行符。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

220

主题

0

回帖

670

积分

高级会员

积分
670

QQ|智能设备 | 粤ICP备2024353841号-1

GMT+8, 2025-3-11 03:17 , Processed in 1.399508 second(s), 26 queries .

Powered by 智能设备

©2025

|网站地图