简体   繁体   中英

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. 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 |
Pear(\s) |

But because the 2 strings have a different length the '|' 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
But I want to get something like this: 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. Ive allocated 13 for skill, 7 for dailyXP, and 10 for weeklyXP, but you could easily modify those values to add a buffer.

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). With a Python F-String it might look like this:

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. 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. This is due to the fact that the characters in non-Monospace fonts have varying pixel widths. A Monospace font, like the name suggests, has a fixed width for all characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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