1. 程式人生 > >python基礎09_字符串格式化

python基礎09_字符串格式化

python clas .html 數字 env IT 方便 really 長度

首先,使用%s 的方法。

#!/usr/bin/env python
# coding:utf-8

# 不用format方法,使用%s 和%d

name = Tom
age = 100

msg = "%s is a good man, 你可以活到 %d 歲." % (name,age) # %d 只能傳數字,所以用%s 最方便
print(msg)

# 對字符串截取
title = "全國各省市平均物價上漲了30%"
ms = "今天的重要新聞是:%.9s" % title  # 截取了9位,可以用來控制長度
print(ms)

# 打印浮點數
tpl = "今天收到了%.2f 塊錢" % 99.325452 #
只保留2位小數且四舍五入 print(tpl) # 打印百分比 用%% tpl = "已完成%.2f%% " % 99.325452 #只保留2位小數且四舍五入 print(tpl) # 使用傳字典的方式 tmp = "I am %(name)s age %(age)d" % {"name":Elly,age:88} print(tmp) tp = "I am \033[45;1m%(name)+20s\033[0m age %(age)d" % {"name":Elly,age:88} print(tp) print(root,x,0,0,sep=:)

接下來,再看看format的一些方法。

更多的可參考:http://www.cnblogs.com/wupeiqi/articles/5484747.html

#!/usr/bin/env python
# coding:utf-8


tpl = I am {name}, age {age}, really {name}.format(name=Tom, age=22) # 傳Key
print(tpl)

tpl = I am {name}, age {age}, really {name}.format(**{name:Jerry, age:33}) # 傳字典 兩星號相當於將字典轉換成上面那行的格式。
print
(tpl) tpl = I am {0[0]}, age {1[0]}, really {1[2]}.format([1,2,3],[11,22,33]) # 傳列表 print(tpl) tpl = I am {:s}, age {:d}, really {:f}.format(Sen,18,88.999) #傳字典 print(tpl) ## 本次參考:http://www.cnblogs.com/wupeiqi/articles/5484747.html l = ["seven", 18] tpl = "i am {:s}, age {:d}".format(*l) # 星號代表將列表中的元素遍歷出來後再傳入 print(tpl) tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2) print(tpl)

python基礎09_字符串格式化