1.\r,把光标移动到行首不换行(比较经典的还是写进度条)
# -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import sys import time import blessings def main(): """Main function.""" char_num = 1 fillchar = '#' cur_progress = '' sharp_list = ['-', '\\', '|', '/'] # sharp width and percent width sharp_width = percent_width = 3 pre_progress_width = int(TERMINAL.width) while True: # real-time change length of the tty width and height progress_width = int(TERMINAL.width) delta_width = progress_width - pre_progress_width chars_width = progress_width - sharp_width - percent_width - 3 # flush current line if delta_width != 0: sys.stdout.write('%s\r' % (' '*progress_width)) sys.stdout.flush() cur_percent = float(char_num) / chars_width cur_charnum = int(round(char_num*cur_percent)) if cur_charnum <= char_num: char_num += 1 else: break cur_sharp = sharp_list[char_num % len(sharp_list)] cur_progress = fillchar * cur_charnum sys.stdout.write('%-*s%-*s %*d%%\r' % ( sharp_width, '[{0}]'.format(TERMINAL.red(cur_sharp)), chars_width, cur_progress, percent_width, int(round(cur_percent*100)))) sys.stdout.flush() time.sleep(0.1) pre_progress_width = progress_width if __name__ == '__main__': TERMINAL = blessings.Terminal() main() print
2.\b,退格键,把输出的光标往回退(比较经典的还是写进度条)
3.\n,换行
4.%s,优先用str()函数进行字符串转换
5.%d,转换对象为有符号的十进制数
6.%o,转换对象为无符号的八进制数
7.%x,转换对象为无符号十六进制数
8.#,在八进制前面显示0,十六进制前面显示0x/X,例%#x,%#o
9.%f,转换对象为浮点型(小数部分自然阶段)
10.-,左对齐,例如%-15s左对齐15个长度
11.+,在正数前面显示加号,例如%+10d,正数前会多一个+号
12.0,在显示的数字前面填充0,例%04d不够4个长度0填充
13.%%,输出一个单一的百分号%,例%%,常用百分比输出
14.(var),例%(hobby)s,后面对应的必须是一个字典
16.m.n,m是显示的最小的总宽度,n是小数点儿后的位数(如果可用的话),可以使用*号作为字段宽度或是精度(或者两者都使用*),此时数值会从元祖参数中读取
# -*- coding: utf-8 -*- """ # # Authors: limanman # OsChina: http://my.oschina.net/pydevops/ # Purpose: # """ import blessings def main(): """Main function.""" price_width = 10 # get total width total_width = int(raw_input('please enter the width: ')) if total_width >= TERMINAL.width: total_width = TERMINAL.width - 2 items_width = total_width - price_width head_format = '%-*s%-*s' item_format = '%-*s%-*.2f' # print header print total_width * '=' print head_format % (items_width, 'Items', price_width, 'Price') print total_width * '=' # print items print item_format % (items_width, 'Linux', price_width, 4999) print item_format % (items_width, 'Python', price_width, 5000) if __name__ == '__main__': TERMINAL = blessings.Terminal() main()