如何实现字符串格式化示例?

2026-05-21 21:141阅读0评论SEO问题
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计331个文字,预计阅读时间需要2分钟。

如何实现字符串格式化示例?

《Python基础教程》中包含一段字符串格式化示例:使用`%`运算符进行格式化。例如:%s用于字符串,%d用于整数,%f用于浮点数。

《python基础教程》里有一段字符串格式化示例:

# coding=utf-8
# 使用指定的宽度打印格式化后的价格列表

width = input('Please enter with: ')

price_width = 10
item_width = width - price_width

header_format = '%-*s%*s'
format = '%-*s%*.2f'

print '=' * width

print header_format % (item_width, 'Item', price_width, 'Price')

print '-'*width

print format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Pears', price_width, 0.5)
print format % (item_width, 'Cantaloupes', price_width, 1.92)
print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)
print format % (item_width, 'Prunes (4 lbs)', price_width, 12)

print '=' * width

运行效果如下:

Please enter with: 35
===================================
Item Price
-----------------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 lbs) 12.00
===================================

Process finished with exit code 0

有几点值得考虑:

1. 用*作为字符的宽度(或精度),它的值从元组中读取;

2. header_format的格式'%-25s%10s',-代表左对齐,那么Item字段所占的宽度为25并且左对齐,Price字段所占宽度为10并且右对齐;

如何实现字符串格式化示例?

3. format的格式为'%-25s%10.2f',比如‘Apples’字段所占的宽度为25并且左对齐,'0.4'字段所占宽度为10并且右对齐,并且字段精度为2,即保留小数点后两位。


本文共计331个文字,预计阅读时间需要2分钟。

如何实现字符串格式化示例?

《Python基础教程》中包含一段字符串格式化示例:使用`%`运算符进行格式化。例如:%s用于字符串,%d用于整数,%f用于浮点数。

《python基础教程》里有一段字符串格式化示例:

# coding=utf-8
# 使用指定的宽度打印格式化后的价格列表

width = input('Please enter with: ')

price_width = 10
item_width = width - price_width

header_format = '%-*s%*s'
format = '%-*s%*.2f'

print '=' * width

print header_format % (item_width, 'Item', price_width, 'Price')

print '-'*width

print format % (item_width, 'Apples', price_width, 0.4)
print format % (item_width, 'Pears', price_width, 0.5)
print format % (item_width, 'Cantaloupes', price_width, 1.92)
print format % (item_width, 'Dried Apricots (16 oz.)', price_width, 8)
print format % (item_width, 'Prunes (4 lbs)', price_width, 12)

print '=' * width

运行效果如下:

Please enter with: 35
===================================
Item Price
-----------------------------------
Apples 0.40
Pears 0.50
Cantaloupes 1.92
Dried Apricots (16 oz.) 8.00
Prunes (4 lbs) 12.00
===================================

Process finished with exit code 0

有几点值得考虑:

1. 用*作为字符的宽度(或精度),它的值从元组中读取;

2. header_format的格式'%-25s%10s',-代表左对齐,那么Item字段所占的宽度为25并且左对齐,Price字段所占宽度为10并且右对齐;

如何实现字符串格式化示例?

3. format的格式为'%-25s%10.2f',比如‘Apples’字段所占的宽度为25并且左对齐,'0.4'字段所占宽度为10并且右对齐,并且字段精度为2,即保留小数点后两位。