Home > Net >  is there a built in method to make all strings the same length by inserting spaces in python without
is there a built in method to make all strings the same length by inserting spaces in python without

Time:09-21

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?

CodePudding user response:

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]¦
  • Related