網站首頁 編程語言 正文
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-11-21 go語言算法題解二叉樹的最小深度_Golang
- 2022-04-06 聊聊c++數組名稱和sizeof的問題_C 語言
- 2023-02-05 Python?面向對象編程詳解_python
- 2022-01-18 Django解決前端/客戶端POST失敗提示csrf_tokenxxx的問題
- 2023-01-03 C#短消息提示窗口位置及窗口大小詳解_C#教程
- 2022-05-22 Python?IO文件管理的具體使用_python
- 2022-09-01 基于MFC實現類的序列化詳解_C 語言
- 2023-07-30 el-selete改變值后選中的內容不變
- 最近更新
-
- 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同步修改后的遠程分支