網站首頁 編程語言 正文
forma格式化的用法
format函數可以接受不限個參數,位置可以不按順序。
基本語法是通過{ }和:來代替c語言的%。
>>> a="名字是:{0},年齡是:{1}"
>>> a.format("煮雨",18)
'名字是:煮雨,年齡是:18'
{0},{1}代表的占位符,數字占位符要注意順序。
>>> c="名字是:{name},年齡是:{age}"
>>> c.format(age=19,name='煮雨')
'名字是:煮雨,年齡是:19'
用format函數實現對齊打印
- 居中對齊 (:^)
- 靠左對齊 (:<)
- 靠右對齊 (:>)
居中對齊示例
def show(n):
tail = "*"*(2*n-1) #最底下一行顯示出(2*n-1)個星號
width = len(tail) #計算星號所在行的寬度,作為其他行的對齊基準
for i in range(1,2*n,2):
print("{:^{}}".format("*"*i,width))
format函數讀取變量時候由外向內:
- { :^{ } },括號讀取變量=="*"*i==
- { :^ { } } ,居中對齊
- { :^ { } } ,最內層括號讀取變量width,作為對齊打印基準
show(5)
輸出結果如下所示:? ? * ? ?
? ?*** ??
? ***** ?
?*******?
********* ? ?#tail變量,顯示出9個星號(n = 5)
右對齊示例
def show(n):
tail = "*"*(2*n-1)
width = len(tail)
for i in range(1,2*n,2):
print("{:>{}}".format("*"*i,width))
show(5)
輸出結果如下所示:? ? ? ? *
? ? ? ***
? ? *****
? *******
*********
左對齊示例
def show(n):
tail = "*"*(2*n-1)
width = len(tail)
for i in range(1,2*n,2):
print("{:<{}}".format("*"*i,width))
show(5)
輸出結果如下所示:* ? ? ? ?
*** ? ? ?
***** ? ?
******* ?
*********
總結
原文鏈接:https://blog.csdn.net/weixin_44630991/article/details/86767601
相關推薦
- 2022-06-30 Python?pickle模塊實現Python對象持久化存儲_python
- 2022-11-14 Git暫存區的意義或git add的意義
- 2022-12-09 python淺拷貝與深拷貝使用方法詳解_python
- 2022-04-15 React+Node實現大文件分片上傳、斷點續傳秒傳思路_React
- 2022-07-07 Golang實現AES加密和解密的示例代碼_Golang
- 2022-05-24 Asp.net?core?使用SignalR推送消息過程詳解_實用技巧
- 2023-12-26 Caused by: org.apache.ibatis.binding.BindingExcept
- 2022-10-26 python的django寫頁面上傳文件及遇到的問題小結_python
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支