How to pad a string to a fixed length with spaces in Python?(如何在 Python 中用空格将字符串填充到固定长度?)
问题描述
我确信这在很多地方都有介绍,但我不知道我正在尝试执行的操作的确切名称,所以我无法真正查找它.我已经阅读了 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 中用空格将字符串填充到固定长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中用空格将字符串填充到固定长度?


基础教程推荐
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01