0

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?

  • Do you actually want to change the string or just want a "nicely" aligned print visualisation? – buran Sep 19 '22 at 10:54
  • Does this answer you question? https://stackoverflow.com/questions/20309255/how-to-pad-a-string-to-a-fixed-length-with-spaces-in-python – Akif Hussain Sep 19 '22 at 10:54
  • Yes there is! The [`str.format()`][1] can be modified to contain width specifiers. [1]: https://docs.python.org/3/library/string.html#format-specification-mini-language – Damiaan Sep 19 '22 at 10:57
  • Does this answer your question? [How to pad a string to a fixed length with spaces in Python?](https://stackoverflow.com/questions/20309255/how-to-pad-a-string-to-a-fixed-length-with-spaces-in-python) – Akif Hussain Sep 19 '22 at 10:58

1 Answers1

2

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]¦
sebtheiler
  • 2,159
  • 3
  • 16
  • 29
  • Thank you. Just to verify, would ```max_name_len= len(max(users.keys(), key=len)) name.ljust(max_name_len+5) ``` work? or would the str.format be better as some others have suggested? – MuteKn0wM0RE Sep 19 '22 at 11:21
  • @MuteKn0wM0RE I find `str.ljust` more readable, but it's honestly just preference – sebtheiler Sep 19 '22 at 18:27