日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python格式化字符串的案例方法_python

作者:〖雪月清〗 ? 更新時間: 2022-05-29 編程語言

1.三種常用格式化字符串方式

1.%作占位符

name = '張三'
age = 10

print('姓名%s,今年%d' % (name, age))

# 運行結果:姓名張三,今年10

%占位符,s和d表示填充的數據類型,順序應與%后括號中的數據變量順序一致

2.使用format()

name = '張三'
age = 10

print('姓名{0},今年{1}歲'.format(name, age))

# 運行結果:姓名張三,今年10歲

{}為占位符,0表示format參數中第一個數據變量 依次類推

3.使用 f 格式化

name = '張三'
age = 10

print(f'姓名{name},今年{age}歲')

# 運行結果:姓名張三,今年10歲

字符串前要加 f 字符串中 {數據變量名} 才能生效

2.字符串寬度和精度的寫法

1.%填充符表示法

# 寬度為10 運行結果:        80
print('%10d' % 80)

# 保留三位小數運行結果:3.142
print('%.3f' % 3.14159)

# 保留三位小數,寬度為10  運行結果:     3.142
print('%10.3f' % 3.1415926)

10為寬度 .3f 為保留三位小數 d為轉化前元素數據類型

注意:如果% 后有多個數據元素,只對第一個數據元素進行格式化

2.format()表示法

# .3表示一共三個數 運行結果:3.14
print('{0:.3}'.format(3.14159))

# .3f表示三位小數  運行結果:3.142
print('{0:.3f}'.format(3.14159))

# 寬度為10 保留三位小數 運行結果:     3.142
print('{0:10.3f}'.format(3.14159))

# 0是占位符的順序, 可以省略 默認為0

例如:

# 運行結果:   256.354
print('{1:10.3f}'.format(3.14159, 256.354))

# 1表示占位符 即format()中參數的順序,從0開始 1就是第二個數據元素 -> 256.354
# 10表示格式化后數據元素的寬度
# .3f表示精度保留三位小數

3.字符串對齊方式

1.center() 居中對齊,第一個參數指定寬度,第二個參數指定填充符,第二個參數是選填的,默認是空格,如果設置寬度小于實際寬度則則返回原字符串

s = 'hello,python'

print(s.center(20, '*'))

# 運行結果:****hello,python****

2.ljust() 左對齊,第一個參數指定寬度,第二個參數指定填充符,第二個參數是選填的,默認是空格,如果設置寬度小于實際寬度則則返回原字符串

s = 'hello,python'

print(s.ljust(20))
# 運行結果:hello,python        

print(s.ljust(20, '*'))
# 運行結果:hello,python********

print(s.ljust(10))
# 運行結果:hello,python

3.rjust() 右對齊,第一個參數指定寬度,第二個參數指定填充符,第二個參數是選填的,默認是空格,如果設置寬度小于實際寬度則則返回原字符串

s = 'hello,python'

print(s.rjust(20))
# 運行結果:        hello, python

print(s.rjust(20, '*'))
# 運行結果:********hello,python

print(s.rjust(10))
# 運行結果:hello,python

4.zfill() 右對齊,左邊用0填充,該方法只接收一個參數,用于指定字符串的寬度,如果指定的寬度小于等于字符串的長度,返回字符串本身

s = 'hello,python'

print(s.zfill(20))
# 運行結果:00000000hello,python

print(s.zfill(10))
# 運行結果:hello,python

原文鏈接:https://blog.csdn.net/qq_52595134/article/details/123169658

相關推薦

欄目分類
最近更新