如何在字符串中添加 X 个空格 [英] How to add X number of spaces to a string

查看:65
本文介绍了如何在字符串中添加 X 个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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:

    offset = 20 - len(word)

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

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

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.

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

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

推荐答案

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

You can multiply by strings by numbers to replicate them.

    printer += ' ' * offset

这篇关于如何在字符串中添加 X 个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆