Python 格式串的用法

Python 中格式串不仅仅是用于 print,还可以直接用来生成特定格式的字符串,类似 C 中的 sprintf。以前就忽略了这个而为 python 没有 sprintf 犯愁。

>>> rate = 9999
>>> s = 'rate: %.2f K/s' % (rate/1024.0)
>>> s
'rate: 97.66 K/s'

另外两种普通的用法是:

1. 用于普通的格式化字符串,类似 C 中的 printf

>>> host='example.org'
>>> port=1208
>>> print 'hostname: %s, port: %d' % (host, port)
hostname: example.org, port: 1208

2. 用字典,好处是字典只需要写一遍,而且不用考虑顺序

>>> dict = { 'host': 'example.org', 'port': 1208 }
>>> print 'hostname: %(host)s, port: %(port)d' % dict
hostname: example.org, port: 1208

0 Comments so far

  1. There are currently no comments.
Leave a Comment?


« 用普通用户身份使用XP  —  Solaris 添加 pkg-get »

Tags

Blogroll

Fairy World | STUPiD | 阅微草堂 | ShelleX | 流浪五天