国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現字符串格式化輸出的方法詳解

2020-02-16 10:16:11
字體:
來源:轉載
供稿:網友

本文實例講述了Python實現字符串格式化輸出的方法。分享給大家供大家參考,具體如下:

python屬于強類型的語言,如果像java一樣操作字符串和數字的“+”時,會出現TypeError。而python的格式化方法有多種,比如使用占位符,使用format,或者是自定義模版等等。這里介紹了其中的幾種方法

下面這個例子很好的說明了python屬于強類型語言:

print "abc" + 123Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: cannot concatenate 'str' and 'int' objects

所以,需要進行轉換輸出。

常用占位符

符號 意思
%s 字符串
%d / %i 十進制整數
%u 過時的十進制使用方法
%o 八進制整數
%x / %X 十六進制整數
%f / %F 浮點數
%e / %E 科學技術法
%% 輸出%

使用方式一

直接使用占位符

print '%s+%d' % ('abc', 123) #abc+123print '%o' % 10 #12 八進制

為%d指定長度,%05d,如果數字小于5位會在左邊補0,大于指定長度時不受此影響

print '%s+%05d' % ('abc', 123) #abc+00123print '%03x' % 10 #00aprint '%.3e' % 123456789 #1.235e+08 保留3位小數的科學技術法

使用方式二

使用字典
代碼如下:print 'Python is %(args)s, %(args)s, %(args)s beautiful' % {'args': 'very'} #Python is very, very, very beautiful
當拼接有許多重復元素時,使用這種方式比較好

使用方式三

使用format的方式。在2.6之后的版本支持。

print '{0}{1}{2}{3}'.format('a', 'b', 'c', 123) #abc123print '{}, {}, {}'.format('a', 'b', 'c') #abc 2.7+ onlyprint '{2}, {1}, {0}'.format('a', 'b', 'c') #c, b, aprint '{2}, {1}, {0}'.format(*'abc') #c, b, aprint '{0}{1}{0}'.format('abra', 'cad') #abracadabra

通過參數名字格式化

print 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W') #Coordinates: 37.24N, -115.81Wcoord = {'latitude': '37.24N', 'longitude': '-115.81W'}print 'Coordinates: {latitude}, {longitude}'.format(**coord) #Coordinates: 37.24N, -115.81W

使用元組

coord = (3, 5)print 'X: {0[0]}; Y: {0[1]}'.format(coord) #X: 3; Y: 5

進制

# format also supports binary numbers"int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42) #'int: 42; hex: 2a; oct: 52; bin: 101010'3 # with 0x, 0o, or 0b as prefix:"int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) #'int: 42; hex: 0x2a; oct: 0o52; bin: 0b101010'            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 格尔木市| 岑溪市| 黑龙江省| 宁武县| 海兴县| 集安市| 临邑县| 金寨县| 晋中市| 措勤县| 博客| 垦利县| 林甸县| 朝阳区| 林芝县| 揭西县| 青冈县| 灌云县| 额尔古纳市| 都匀市| 凤翔县| 广水市| 赤城县| 新蔡县| 赣州市| 崇义县| 垫江县| 岑巩县| 永泰县| 电白县| 鹤壁市| 桂平市| 隆尧县| 延庆县| 柞水县| 通城县| 稷山县| 平度市| 奈曼旗| 美姑县| 吴忠市|