zoukankan      html  css  js  c++  java
  • 字符串格式化示例

    《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,即保留小数点后两位。

  • 相关阅读:
    关于android listview去掉分割线
    关于android在Service中弹出Dialog对话框
    Java SimpleDateFormat 函数
    关于Android使TextView可以滚动的设置
    关于Android(Java)创建匿名线程
    关于解决 Failed to prepare partial IU:
    毕业设计进度:2月4日
    毕业设计进度:2月3日
    毕业设计进度:2月2日
    毕业设计进度:2月1日
  • 原文地址:https://www.cnblogs.com/my_captain/p/8681095.html
Copyright © 2011-2022 走看看