Python:字符串格式化
2012-02-08 16:28
495 查看
字符串格式化:
%:
%s 格式化为字符串
模板字符串:
关键字参数(substitute):
单词替换
用*作为字段宽度或精度
转换标志:
-:左对齐
+:在转换值之前加上正负号
“ ”:正数之前保留空格
0:转换值若位数不够用0填充
字符串格式化范例
结果显示:
%:
%s 格式化为字符串
>>> format = "Hello, %s. %s enough for ya?" >>> values = ('world', 'Hot') >>> print format % values Hello, world. Hot enough for ya?%f 格式化为实数(浮点数)
>>> format = "Pi with three decimals: %.3f"//保留小数点后3个有效数字 >>> from math import pi//导入pi的值 >>> print format % pi Pi with three decimals: 3.142
模板字符串:
关键字参数(substitute):
单词替换
>>> from string import Template >>> s = Template('$x, gloriout $x!') >>> s.substitute(x = 'slurm') 'slurm, gloriout slurm!'单词字母替换
>>> from string import Template >>> s = Template("It's ${x}tastic!") >>> s.substitute(x = 'slurm') "It's slurmtastic!"用$$插入$符号
>>> from string import Template >>> s = Template("Make $ selling $x!") >>> s.substitute(x = 'slurm') 'Make $ selling slurm!'字典变量提供值
>>> from string import Template >>> s = Template('A $thing must never $action') >>> d = {} >>> d['thing'] = 'gentleman' >>> d['action'] = 'show his socks' >>> s.substitute(d) 'A gentleman must never show his socks'
用*作为字段宽度或精度
>>> '%.*s' % (5, 'Guido van Rossum') 'Guido'
转换标志:
-:左对齐
+:在转换值之前加上正负号
“ ”:正数之前保留空格
0:转换值若位数不够用0填充
>>> pi = 3.1415 >>> '%010.2f' % pi '0000003.14' >>> '%-10.2f' % pi '3.14 ' >>> '%10.2f' % pi ' 3.14' >>> '% 10.2f' % pi ' 3.14' >>> '%+10.2f' % pi ' +3.14'
字符串格式化范例
width = input('Please enter width: ') 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)
结果显示:
Please enter width: 35 =================================== Item Price ----------------------------------- Apples 0.40 Pears 0.50 Cantaloupes 1.92 Dried Apricots (16 oz.) 8.00 Prunes (4 lbs.) 12.00
相关文章推荐
- Python中用%号格式化字符串
- Python语言基础(二) -- 字符串格式化
- (转)Python 字符串格式化 (%操作符)
- Python实现字符串格式化的方法小结
- python3----字符串格式化(format)
- Python-格式化字符串
- python字符串格式化
- python,格式化字符串函数.format()的用法
- python 之 格式化字符串函数format()
- Python字符串格式化
- Python字符串格式化
- python字符串格式化
- Python——format字符串格式化
- Python中用format函数格式化字符串的用法
- Python中用format()格式化字符串
- Python 字符串格式化
- 第二天 Python3.4.2 字符串的格式化 和 常用操作
- python基础之字符串格式化
- Python中用format函数格式化字符串的用法
- 【Python】08、字符串格式化、编码及bytes、bytearray