1. 程式人生 > >2018/11/6(python)

2018/11/6(python)

spa div clas span 字典 format 浮點 col int

1.百分號字符串拼接

s="i am %s,i like playing basketball"%"alex"
print(s)

s="i am %s,i like playing %s"%("alex","basketball")         #%s可以接受一切,%d只能接受數字
print(s)


a="alex"
b="basketball"
s="i am %s,i like playing %s"%(a,b)                 #接受變量
print(s)

#浮點數
x="%.3f"% 3.141592657
print(x)

#打印百分比(%%)
x="
%.3f %%"% 3.141592657 print(x) #傳字典 s="i am %(a)s,i like playing %(b)s" % {"a":"alex","b":"basketball"} print(s)

2.format 字符串格式化

#默認一一對應
s="i am {} years old,i like {},i have {} sister".format("4","5","6")
print(s)

#指定對應
s="i am {2} years old,i like {1},i have {0} sister".format("4
","5","6") print(s) #字典形式 s="i am {age} years old,i like {num},i have {sister} sister".format(age="4",num="5",sister="6") print(s) #取列表中的元素 s="i am {0[1]} years old,i like {0[2]},i have {1[1]} sister".format([1,2,3],[4,5,6]) print(s)

2018/11/6(python)