問題描述
我確信這在很多地方都有介紹,但我不知道我正在嘗試執行的操作的確切名稱,所以我無法真正查找它.我已經閱讀了 30 分鐘的官方 Python 書籍,試圖找出如何做到這一點.
I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.
問題:我需要在一定長度的字段"中放入一個字符串.
Problem: I need to put a string in a certain length "field".
例如,如果姓名字段有 15 個字符長,而我的名字是 John,我會得到John"后跟 11 個空格來創建 15 個字符的字段.
For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.
我需要它適用于為變量name"輸入的任何字符串.
I need this to work for any string put in for the variable "name".
我知道這可能是某種形式的格式,但我找不到執行此操作的確切方法.幫助將不勝感激.
I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.
推薦答案
這是超級簡單的format
:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
這篇關于如何在 Python 中用空格將字符串填充到固定長度?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!