4.3 Python中的字符串格式化
程序员文章站
2022-09-10 11:19:29
将字符按指定格式输出,可以在python2.7的chm帮助文档中检索:formatting
可找到fromatting.string(%)帮助主题
比如:
>>...
将字符按指定格式输出,可以在python2.7的chm帮助文档中检索:formatting
可找到fromatting.string(%)帮助主题
比如:
>>> print('输出数字:%d'%5) 输出数字:5 >>> print('输出浮点数字:%f'%0.005) 输出浮点数字:0.005000 >>> print('输出十六进制数字:%x'%108) 输出十六进制数字:6c >>> print('输出百分比数字:%f%%'%10.8) 输出百分比数字:10.800000% >>> num=123 >>> 'dec:%d;oct:%#o;hex:%#x'%(num,num,num) 'dec:123;oct:0173;hex:0x7b' >>> 'mm/dd/yy=%02d/%02d/%d'%(2,16,90) 'mm/dd/yy=02/16/90' >>> print('host:%s\tport:%d'%('local',8080)) host:local port:8080 >>> w,i='web','index' >>> 'https://www.baidu.com/%s/%s.html'%(w,i) 'https://www.baidu.com/web/index.html' >>> for i in range(9): print('https://xxx.com/page_%d.htm'%i) https://xxx.com/page_0.htm https://xxx.com/page_1.htm https://xxx.com/page_2.htm https://xxx.com/page_3.htm https://xxx.com/page_4.htm https://xxx.com/page_5.htm https://xxx.com/page_6.htm https://xxx.com/page_7.htm https://xxx.com/page_8.htm
其它函数
>>> a='a' >>> b='b' >>> c='c' >>> cmp(a,b) -1 >>> cmp(c,b) 1 >>> cmp(a,a) 0 >>> a='a' >>> b='b' >>> c='c' >>> cmp(a,b) -1 >>> cmp(c,b) 1 >>> cmp(a,a) 0 >>> max('abcdef') 'f' >>> min('abce') 'a' >>> chr(65) 'a' >>> ord('a') 97
更多字符串操作内建函数可通过dir(string)查询
下一篇: 煮毛豆冷水还是热水下锅