How to go about replacing words

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


I’ve been having an issue trying to replace specific words within my text.

So I’ve been trying to put together a text based game. I moved from Twine 2, specifically Sugarcube 2, to Godot as I felt that would be a better choice for a full game.

Now Sugarcube 2 had this handy little API that would allow you to take a placeholder word and replace it. How that word was replaced could depend on a variable or could be randomly selected from an array.

Say for example your sentence was “You pet the ?animal”
You would create a template for ?animal that would find each instance of ?animal in your text and spit out a replacement like “dog”, “cat”, or even “giant fire breathing dragon” if you wanted.

So I’ve been trying get something similar going, but I’ve had very little luck so far. Format strings looked somewhat close, but didn’t seem quite right for my purposes.

Any help with this would be greatly appreciated.

:bust_in_silhouette: Reply From: Noelb

There’s a page in the docs on how to do this here:
GDScript format strings

var actual_string = “We’re waiting for %s.” % “Godot”
var actual_string = “%s was reluctant to learn %s, but now he enjoys it.” % [“Estragon”, “GDScript”]

I’m aware. As I said, I looked at Format Strings and found that, while they are close, they’re not quite the right solution.

Using the Format Strings method means I have no way of differentiating between my placeholders as they seem to follow a generic placeholder type. (%s, %c, %d, etc…)

As the bulk of my work will be writing scenes, dialogue, and their variations, I need to be able to write my placeholders in my text so I can easily swap them out. I can’t easily swap out my keywords if my text looks like “%s and %s ran up the %s to fetch a bucket of %s.” This leads to my second issue. I still need a way to pick out the placeholders in my text and replace them.

The only way I can see Format Strings working even remotely for my purposes would be to put all of my scenes, dialogue, and their variations into a script, define my placeholders, and then push the result to a label. Of course then that means I’m either writing a bunch of scripts for each scene, dialogue, and their variations, or throwing as much as I can into as few scripts as I can. Either solution feels like it would just be making things either overly complicated or extremely tedious.

The intended end goal here would be to simply have a script that would run in the background that either has all of my keywords listed, or reads from another file that does, and then replaces them in my text automatically with whatever definition each keyword has whether it’s a random array or based on a variable.

Volk | 2022-07-08 04:47