Python 如何在字符串中添加 X 个空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23835810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:30:04  来源:igfitidea点击:

How to add X number of spaces to a string

pythonpython-2.7

提问by Mitch

Probably an easy question that I couldn't quite find answer to before...

可能是一个简单的问题,我以前找不到答案......

I'm formatting a table (in text) to look like this:

我正在格式化一个表格(在文本中),如下所示:

Timestamp: Word                        Number

The number of characters between the : after timestamp and the beginning of Number is to be 20, including those in the Word (so it stays aligned). Using python I've done this:

: 时间戳之后和 Number 开头之间的字符数为 20,包括 Word 中的字符数(因此它保持对齐)。使用 python 我已经做到了:

    offset = 20 - len(word)

    printer = timestamp + ' ' + word
    for i in range(0, offset):
        printer += ' '
    printer += score

Which works, but python throws an error at me that i is never used ('cause it's not). While it's not a huge deal, I'm just wondering if there's a better way to do so.

哪个有效,但是 python 向我抛出一个错误,我从未使用过(因为它不是)。虽然这不是什么大问题,但我只是想知道是否有更好的方法来做到这一点。

Edit:

编辑:

Since I can't add an answer to this (as it's marked duplicate) the better way to replace this whole thing is

由于我无法对此添加答案(因为它被标记为重复),因此替换整个事情的更好方法是

printer = timestamp + ' ' + word.ljust(20) + score

采纳答案by merlin2011

You can multiply by strings by numbers to replicate them.

您可以将字符串乘以数字来复制它们。

    printer += ' ' * offset

回答by wastl

Try

尝试

printer += ' '*offset

instead of the for-loop

而不是 for 循环

回答by iruvar

String formatting may work too

字符串格式也可以工作

'{}: {: <20s}{}'.format("Timestamp", "Word", 200)
Timestamp: Word                200