GDScript Format String Tutorial – Complete Guide

Welcome to this comprehensive tutorial on GDScript format strings. This guide aims to provide with you a solid understanding of one of the most essential concepts in the world of coding, particularly in the context of game development.

What is a Format String in GDScript?

In GDScript – the scripting language used in Godot Engine game development – a format string is a special type of string that contains placeholders. These placeholders are filled with specified values to generate a new, dynamic string.

What is it Used For?

With GDScript’s format strings, you can create more flexible and dynamic dialogue, in-game text, debugging logs, and much more. It is a critical feature for creating interactive and immersive game experiences.

Why Should I Learn About Format Strings?

Mastering the use of format strings allows you more control over your game’s user experience. Given the interactive nature of games, the ability to generate dynamic text is invaluable. Additionally, learning about format strings also strengthens your overall programming skill set.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Use of Format Strings in GDScript

The simplest way to utilize a format string in GDScript is to define a string with placeholders, then use the % operator followed by a tuple of values. This will fill the placeholders in the order they were defined.

var a = 5
var b = 10
var result = "The sum of %d and %d is %d." % (a, b, a + b)
print(result)  # Outputs: The sum of 5 and 10 is 15.

Notice how we use %d as a placeholder for decimal numbers. Different placeholders are used for different types of data.

Handling Different Data Types with Format Strings

GDScript format strings can handle various data types. Here are the common placeholders:

  • %d for decimals (integers).
  • %f for floating point numbers.
  • %s for strings.
var string = "Zenva"
var float_num = 5.3
var int_num = 20
var result = "%s offers over %d courses on coding and <a class="wpil_keyword_link" href="https://gamedevacademy.org/how-to-learn-coding-for-beginners/" target="_blank" rel="noopener" title="game development" data-wpil-keyword-link="linked">game development</a>, with a rating of %f." % (string, int_num, float_num)
print(result)  # Outputs: Zenva offers over 20 courses on coding and game development, with a rating of 5.3.

Specifying Field Width and Precision

In format strings, you can control the field width and precision of numerical values. This is helpful when you want to format scores, times, or other numerical game data.

var float_num = 5.36789
var result = "Your final score is %.2f!" % float_num
print(result)  # Outputs: Your final score is 5.37!

In the example above %.2f tells GDScript to format the floating point number to two decimal places.

Using Alignment and Padding Options

Format strings also allow you to adjust alignment and apply padding, offering more control over the appearance of your game text, scores, or other critical information.

var score = 150
var result = "%05d points" % score
print(result)  # Outputs: 00150 points

In the example above, the %05d placeholder aligns the output to the right, padding it with zeros up to a length of 5 characters.

Using Argument Index in Format Strings

At times, you might want to reuse variables or control their order without changing the tuple order. This is made possible by using argument index (0-based) in your placeholders.

var arg1 = "Zenva"
var arg2 = "coding"
var result = "%s offers over 100 courses focused on %s. Join the %s community today!" % [arg1, arg2, arg1]
print(result)  # Outputs: Zenva offers over 100 courses focused on coding. Join the Zenva community today!

In the above example, we use the index (0-based) to refer back to ‘Zenva’ and ‘coding’ as needed, giving us more control and flexibility in formatting our strings.

Adding a Dictionary to Format Strings

Sometimes, your format strings could be more complex, or maybe you need a more self-describing and intuitive way to handle string formatting. In such cases, you can use a dictionary.

var data = {"company": "Zenva", "courses": 100}
var result = "%(company)s offers over %(courses)d courses focused on coding. Join the %(company)s community today!" % data
print(result)  # Outputs: Zenva offers over 100 courses focused on coding. Join the Zenva community today!

Notice how we are using keys from our dictionary in the placeholder. It offers a clear understanding of what output to expect from the given format string.

Mastering GDScript format strings is a stepping stone to creating rich, dynamic, and immersive game experiences. Keep practicing and boosting your game development skills with us, and create amazing games with Godot Engine.

Escaping Special Characters in Format Strings

While dealing with format strings, you may frequently encounter special characters. You can handle them using an escape sequence %%.

var percent_complete = 75
var result = "The game download is %d%% complete." % percent_complete
print(result)  # Outputs: The game download is 75% complete.

Notice how we used %% to escape the percent symbol.

Writing Multiline Format Strings

At times, your format strings might span across multiple lines, especially when formatting longer pieces of text. You can manage these situations with tripe-quoted strings.

var stats = {"player": "John Doe", "level": 10, "score": 2000}
var result = """Player Stats:
Name: %(player)s
Level: %(level)d
Score: %(score)d""" % stats
print(result)  # Outputs: 
# Player Stats:
# Name: John Doe
# Level: 10
# Score: 2000

Notice in the example above how we use triple quotes to define a multiline format string.

Using Logic in Format Strings

GDScript format strings can also be used in conjunction with logical conditions to construct complex sentences or handle various user inputs or actions within your game.

var level = 10
var message = "You are %s the halfway mark." % ("above" if level > 5 else "below")
print(message)  # Outputs: You are above the halfway mark.

In this example, we used a ternary conditional operator within our format string to construct a dynamic message based on the player’s level.

Using Format Strings for Debugging

GDScript format strings can be particularly helpful in debugging your code by formatting and printing variable states, error messages, or other relevant information.

var player_pos = Vector2(10, 20)
var enemy_pos = Vector2(15, 25)
print("Player Position: %s, Enemy Position: %s" % [str(player_pos), str(enemy_pos)])
# Outputs: Player Position: (10, 20), Enemy Position: (15, 25)

This debugging statement gives a snapshot of the player’s and enemy’s positions, proving crucial for any fixes or optimization needed.

By strategically employing GDScript format strings, you can develop more compelling and easier-to-maintain game code. We at Zenva encourage you to utilize these techniques to enhance your coding skills and bring your game ideas to life.

With a newfound understanding of GDScript format strings, where should you go next on your coding journey? We recommend that you consider diving even deeper into the world of game development with Zenva’s Godot Game Development Mini-Degree. This robust program offers a multitude of courses designed to help you build cross-platform games using the Godot engine. You’ll learn about using 2D and 3D assets, controlling gameplay, managing player and enemy combat, implementing UI systems, and mastering various game mechanics. Whether you’re a complete beginner or an advanced developer, this curriculum offers step-by-step guidance that you can tailor to your current skill level.

Moreover, our catalogue is also full of other Godot courses that cover both fundamental and advanced areas of game development. Each course comes with engaging and interactive lessons, challenging coding tasks, and a completion certificate upon finishing the course. All are designed with the objective of enhancing your career prospects in the growing games market.

At Zenva, we strive to empower our learners, enabling you to go from beginner to professional. Start learning with us today, continue honing your coding skills, and start bringing your most ambitious game ideas to life!

Conclusion

Format strings in GDScript are an essential part of creating dynamic and user-centric interactions in your Godot games. By mastering their use, you can create more meaningful and engaging gameplay, debugging and game testing systems, and everything in between.

The ability to generate dynamic in-game text is invaluable for crafting a truly immersive game experience. At Zenva, it gives us immense joy to enable learners like yourself to harness this powerful tool and create amazing games. Start expanding your game development skills today with our Godot Game Development Mini-Degree!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.