Concatenate strings and integers

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By csmith17979
:warning: Old Version Published before Godot 3 was released.

How would you go about showing text on screen with an integer and string, ie: showing a stats/records screen where it says something like wins: 5 losses: 2?

I was guessing it would be something along the lines of:

extends Label
var x = 5
var y = 2
func _ready():
  set_text("wins: " + x + "Losses: " + y)

However, this doesn’t seem to work.

Also, how would I go about adding a line, to get this:

Wins: 5
Losses: 2
:bust_in_silhouette: Reply From: unaware

You can do that if you add str() to each of those variables to turn them into strings. You can also use a newline to add a line. The revised line would look like this: set_text("wins: " + str(x) + "\nLosses: " + str(y))

:bust_in_silhouette: Reply From: ndee

You can also but everything into str()

label.set_text(str("wins: ", x , "Losses: ", y))

BTW, I guess you meant “put” and not “but” :slight_smile:

Bojidar Marinov | 2016-02-24 15:53

:bust_in_silhouette: Reply From: bluenote

It is even more elegant to use format strings:

set_text("Wins: %d Losses: %d" % [x, y])

The benefit of using % from the start is that you could easily change the code later so that the output has more structured formatting. For instance, if you later want to give the literals a fixed width of 10 chars, you could use %10d.

Definitely this. This is the entire purpose that format strings serve.

Epidal | 2019-12-22 21:04