使用 format
text = 'world'
print('hello {}'.format(text))
# hello world
name = 'Jack'
text = 'world'
print('hello {name}, hello {text}'.format(name=name, text=text))
# hello Jack, hello world
string
— Common string operations
>>> '{0}, {1}, {2}'.format('a', 'b', 'c') 'a, b, c' >>> '{}, {}, {}'.format('a', 'b', 'c') # 3.1+ only 'a, b, c' >>> '{2}, {1}, {0}'.format('a', 'b', 'c') 'c, b, a' >>> '{2}, {1}, {0}'.format(*'abc') # unpacking argument sequence 'c, b, a' >>> '{0}{1}{0}'.format('abra', 'cad') # arguments' indices can be repeated 'abracadabra' >>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) 'int: 42; hex: 2a; oct: 52; bin: 101010' >>> '{:+f}; {:+f}'.format(3.14, -3.14) # show it always '+3.140000; -3.140000'
#end 預設換行 print('a' , 'b' , 'c' ) -> a b c #sep 分隔 end結束為空白無換行 print('a' , 'b' , 'c' , sep="," , end= " ") -> a,b.c
# % 做資料的分隔,不是逗號 print("%3d" % 42)) print("%2d %2d " % (42 , 45))
#使用 .format (文字 < 置左 >置右) {0}第一個參數 ... print("{0:<20s} {1:6.2f}".format('Spam & Eggs:' , 7.99) ) -> Spam & Ham: 7.99