How to format text to create spaces between variables

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By leo-pnt

Hello everybody !

I have Labels that show informations about the player:

acceleration_label.text = "acceleration........." + str(player_acc)
velocity_label.text = "velocity................." + str(player_vel)

the output is for instance:
acceleration…3.4
velocity…209.7

Is there an easy way to have this instead ?:
acceleration…3.4
velocity…209.7

Or do I have to code it myself ?

Thanks for your time

:bust_in_silhouette: Reply From: jgodfrey

A few thoughts…

If you want both the text label and the value to be rendered as part of a single string in a single Label component, you’ll need to use a fixed-width font. In that case, each character in the font will take the same amount of space. With that, you could easily calculate the amount of space needed between a given text label and its value to properly align the columns in multiple rows. Without a fixed-width font, it’s probably not possible.

Alternatively, if you could represent the two pieces of data in each row in 2 separate Label components (1 for the text and 1 for the number), it’d be easier to handle the alignment. In that case, you’d just need to separate the two “columns” of labels appropriately, and then format your values to properly align. The advantage here is that you don’t have to deal with the variable-length text portions also…

Though, no matter what, you’ll have to do some work yourself.

One more thought, though I’m not overly familiar… Perhaps the RichTextLabel node supports some formatting options that might be useful here?

Ok thanks,
The fixed-width font worked with a bit of code on the strings

I multiplied the length of the value string (“209.7”.length() = 5) with the number of spaces and subtracted the result from a constant number of spaces
so:
“…” - (5 * “.”) = “…”

then you can add “209.7” and you have “…” + str(209.7) = “…209.7”

for those interested, here is the code

var spaces = subTxt("     ", multTxt(" ", str(velocity).length()))
velocity_label.text = "VELOCITY:" + spaces + str(speed)

func multTxt(txt, nb):
	var newText = ""
	for _i in range(nb):
		newText += txt
	return newText

func subTxt(txt1, txt2):
	var newSize = txt1.length()-txt2.length()
	return txt1.substr(0, newSize)

That way, the total string is always the same length.
I have a bit of flickering when the values changes fast but it’s ok, all my players informations are aligned.

leo-pnt | 2020-04-29 19:50