【python】print输出的格式化

140 篇文章 0 订阅

在Python中,有几种方式来格式化prin`函数的输出。以下是一些常见的方法:

1. 使用百分号 % 运算符(传统方法):

使用 % 操作符来进行格式化是一种较老的方法,但它仍然有效。

   name = "Alice"
   age = 25
   print("Hello, %s. You are %d years old." % (name, age))

2. 使用`str.format()`方法:

str.format() 提供了一种更现代、更灵活的方式来格式化字符串。

   name = "Alice"
   age = 25
   print("Hello, {}. You are {} years old.".format(name, age))
   # 或者使用索引指定顺序:
   print("Hello, {0}. You are {1} years old.".format(name, age))
   # 还可以使用关键字:
   print("Hello, {name}. You are {age} years old.".format(name=name, age=age))

3. 使用f-string(从Python 3.6起引入的格式化字符串字面值):

从Python 3.6开始,可以使用f-strings来格式化字符串,这是一种非常简洁的方法。在字符串前加上 f 前缀,然后在 {} 中放入变量或表达式。

   name = "Alice"
   age = 25
   print(f"Hello, {name}. You are {age} years old.")

还可以在 {} 中直接执行计算和调用方法:

print(f"Next year, I will be {age + 1} years old.")

4. 使用格式化字符填充和对齐:

   data = {"name": "Alice", "age": 25}
   # 右对齐
   print("{:>10} {:>10}".format(data['name'], data['age']))   # 输出:'     Alice         25'
   # 左对齐
   print("{:<10} {:<10}".format(data['name'], data['age']))   # 输出:'Alice      25       '
   # 居中
   print("{:^10} {:^10}".format(data['name'], data['age']))   # 输出:'  Alice        25   '

5. 使用格式化指定小数点精度:

   number = 3.14159265359
   print("{:.2f}".format(number))  # 输出:3.14

6. 使用格式化来做零填充:

   number = 5
   print("{:02d}".format(number))  # 输出:05

7. 使用print函数的sep和end参数:

这些参数可以用来控制print函数输出时各个值之间的分隔符,以及输出结束后的字符。默认情况下,sep=' '(一个空格),end='\n'(一个换行符)。

print("Hello", "world", sep="-", end="!!!")  
# 输出:Hello-world!!!

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

109702008

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值