如何用Python中的空格填充一个固定长度的字符串? [英] How to pad a string to a fixed length with spaces in Python?
问题描述
问题:我需要把一个字符串放在一定长度的字段中。例如,如果name字段长度为15个字符,而我的名字是John,那么我会得到John,接着是11个空格来创建15个字符的字段。
我需要这个工作为变量名称的任何字符串。
我知道这可能是某种形式的格式化,但我找不到确切的方法来做到这一点。帮助将不胜感激。
$ 格式
:
$ b
>>> a =John
>>>格式(a)
'John'
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".
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.
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.
This is super simple with format
:
>>> a = "John"
>>> "{:<15}".format(a)
'John '
这篇关于如何用Python中的空格填充一个固定长度的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!