網站首頁 編程語言 正文
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
相關推薦
- 2022-04-06 關于.Net?6?添加NLog的方法_實用技巧
- 2024-01-16 解決 git pull 操作后文件權限變化
- 2024-02-27 Go 讀取控制臺輸入
- 2023-07-14 react 中redux的使用步驟
- 2022-02-19 RHCE安裝Apache,用瀏覽器訪問IP_Linux
- 2022-02-24 使用Nginx和Lua進行JWT校驗介紹_nginx
- 2022-08-26 Redis哨兵模式實現一主二從三哨兵_Redis
- 2022-08-15 centos7 redis5安裝
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支