[SOLVED] is there a built in method to make all strings the same length by inserting spaces in python without using a bunch of for loops and max/len?

Issue

This Content is from Stack Overflow. Question asked by MuteKn0wM0RE

Is there a way I can evenly space the text?

I want this:

var_to_change: ¦[3][10]¦

james: ¦[7][A]¦

To look like this:

var_to_change: ¦[3][10]¦

james:         ¦[7][A]¦

Below is my current code for printing (part of a bigger function):

# hand is formatted [card1, card2]
 disp_hand = f'{player}: ¦'
    for card in hand:
        disp_hand += '[' + str(card) + ']' 
    disp_hand += '¦ n'
    print(disp_hand)

I was thinking of the len(max()) function to get the length of the biggest string and then inserting spaces for all names using a for spaces in range (len(max()) - len(name)): loop and adding spaces until they match the max string length but this is quite complex and I was wondering whether there is a better way.

Below is a method I came up with:

users = {'john': {'hand': [1,2]},'var_to_change': {'hand': [1,2]}}

max_name_len= len(max(users.keys(), key=len))
name_dif = {}

for names in users:
    name_dif[names] = max_name_len-len(names)
    
for names in users.copy():
    whitespace = ''
    for spaces in range(name_dif[names]):
        whitespace += ' '
    users[names + whitespace] = users.pop(names)

print(users) # returns: {'john         ': {'hand': [1, 2]}, 'var_to_change': {'hand': [1, 2]}}

Are there any built-in methods or better ways?



Solution

Try using str.ljust

print("var_to_change:".ljust(15), "¦[3][10]¦")
print("james:".ljust(15), "¦[7][A]¦")

# Output:
var_to_change:  ¦[3][10]¦
james:          ¦[7][A]¦


This Question was asked in StackOverflow by MuteKn0wM0RE and Answered by sebtheiler It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?