Python——佔位的幾種運用形式

%號佔位符

%轉換形式

%[ 轉換標記 ][ 寬度 [ .精確度] ] 轉換類型

轉換標記 解釋 樣例
- 左對齊(默認右對齊) print “the number is %-9f” % 1991
+ 在正數後加上+ print “the number is %+9f or %+0.9f” % (1991,-1991)
(a space) 正數之前保留空格 print “the number is % 0.1f” % 1991
# 顯示進制標識 print “the number is %#x” % 1991
0 位數不夠0來湊 print “the number is %010.2f” % 1991
  • %s 採用str方式字符串輸出
# 普通佔位
print "hello %s" % "world" 
# 多值佔位
print "hello %s,i'm %s" % ("world", "python")
# 指定佔位長度
print "I‘m %s, I was born in %6s" % ('python',1991)
# I‘m python, I was born in   1991    1991佔6位右對齊  相當於字符串的rjust方法
print "I‘m %s, I was born in %-6s" % ('python',1991)
# I‘m python, I was born in 1991    1991佔6位左對齊  相當於字符串的ljust方法
# 字符串居中可以使用字符串的center方法
# 鍵值對佔位
print "I‘m %(name)s, I was born in %(born)s" % {'name':'python','born':'1991'}
  • %r 採用repr方式顯示
# 簡單來說str更人性化,repr更精確。str旨在可讀性上(對人),repr旨在標準上(對機器)。
print "%r" %"\n你好\n" 
'\n\xe4\xbd\xa0\xe5\xa5\xbd\n'
print "%s" %"\n你好\n" 

你好

format

轉換形式

[[填充符]對齊方式][符號][#][0][寬度][,][.精確度][轉換類型]

對齊方式 解釋
< 左對齊
> 右對齊
= 僅對數值型有效,如果有符號,在符號後數值前進行填充
^ 居中對齊,用空格填充
符號 解釋
:–: :-:
+ 正數前加+,負數前加-
- 正數前不加符號,負數前加-
空格 正數前加空格,負數前加-
佔位使用

“{0}-{1}-{2}”.format(‘a’,‘b’,‘c’)
“{a}-{b}-{c}”.format(a=1,b=2,c=3)

直接使用

format(1995,‘0>+10.3f’)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章