简体   繁体   English

当我有多个不同长度的字符串时,有没有办法将一个字符放在所有字符串的相同索引处

[英]Is there a way when i have multiple strings with different lengths to place a character at the same index for all strings

I am making a discord bot in python.我正在 python 中制作 discord 机器人。 Today I scraped a website and I wanted to make a string with all the info I scraped.今天我抓取了一个网站,我想用我抓取的所有信息制作一个字符串。 The problem I am having is that I want to create a vertical line between the different sections, but some strings are longer then others, for example I want to create this:我遇到的问题是我想在不同部分之间创建一条垂直线,但是有些字符串比其他字符串长,例如我想创建这个:

Apple \s |苹果\s |
Pear(\s) |梨(\s) |

But because the 2 strings have a different length the '|'但是因为 2 个字符串的长度不同,所以 '|' won't be a straight line.不会是一条直线。 The code I have right now is this:我现在的代码是这样的:

def print_tracked_xp(self, XpDict):
        trackedStuff = """Skill    | Today's XP    | Yesterday's XP    | Weekly XP    \n"""
    for key in XpDict:
        trackedStuff += key + '    | ' + XpDict[key]['Daily XP'] + '    | ' + XpDict[key]['Yesterdays XP'] + '    | ' + XpDict[key]['Weekly XP'] + '\n'
    return trackedStuff

As output i get this: https://imgur.com/FbZlTZd作为 output 我得到这个: https://imgur.com/FbZlTZd
But I want to get something like this: https://imgur.com/VXxIP75但我想得到这样的东西: https://imgur.com/VXxIP75

I would use string formatter in your print statement.我会在您的打印语句中使用字符串格式化程序。 Anything specified after the colon is the number of characters reserved for the variable in the print statement.冒号后指定的任何内容都是为 print 语句中的变量保留的字符数。 Ive allocated 13 for skill, 7 for dailyXP, and 10 for weeklyXP, but you could easily modify those values to add a buffer.我为技能分配了 13 个,为dailyXP 分配了7 个,为每周XP 分配了10 个,但是您可以轻松地修改这些值以添加缓冲区。

print('{0:13} | {1:7} | {2:7} | {3:10}'.format(skill, todayXP, yesterdayXP, weeklyXP))

There are two things to be aware of:有两点需要注意:

1.) You will need to pad your strings with a certain number of spaces, and justify the string (left, center or right). 1.) 您需要用一定数量的空格填充字符串,并对齐字符串(左、中或右)。 With a Python F-String it might look like this:使用 Python F-String 可能如下所示:

strings = [
    "Strength",
    "Intelligence"
]

for string in strings:
    print(f"{string:<20}|")

2.) From the picture you posted, I can see that the terminal (in which the output you're getting is displayed) does not seem to be using a Monospace font. 2.)从您发布的图片中,我可以看到终端(其中显示了您获得的 output)似乎没有使用等宽字体。 If the terminal you're printing your output to does not have a Monospace font, it doesn't matter how correctly you pad your strings with spaces - everything will be misaligned.如果您打印 output 的终端没有等宽字体,那么用空格填充字符串的正确程度并不重要 - 一切都会错位。 This is due to the fact that the characters in non-Monospace fonts have varying pixel widths.这是因为非等宽字符 fonts 中的字符具有不同的像素宽度。 A Monospace font, like the name suggests, has a fixed width for all characters.顾名思义,等宽字体对所有字符都有固定的宽度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM