我在列印陳述句中使用使用 .format() 函式的簡單代碼填充輸出
print('{:-<100}'.format('xyz'))
通過創建一個新變數,我能夠使用 f-strings 獲得類似的輸出
library = 'xyz'
print(f'{library:-<100}')
問題:有沒有辦法'xyz'在 f-string 中添加字串而無需創建新變數?
我嘗試了下面的代碼,但它給了我一個錯誤:
print(f'xyz:-<100')
uj5u.com熱心網友回復:
如果我沒記錯的話,你想做的是:
print(f"{'xyz':-<100}") # You can use expressions here, not only variables!
PS:關于錯誤,你確定你運行的是 Python 3.6 嗎?
uj5u.com熱心網友回復:
如果我理解你的問題是正確的,那么:
您可以在單引號 f 字串中使用雙引號字串
print(f'{"xyz":-<100}')
和可選的,沒有 f-string 和格式
print("xyz".ljust(100, "-"))
uj5u.com熱心網友回復:
是的,有一種方法可以在 fstring 中添加字串 ('xyz'),而無需創建新變數。
只需在大括號 '{}' 外添加字串 'xyz'
示例: print(f'xyz{:-<100}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451050.html
標籤:Python python-3.x 细绳 格式化
