5

I couldn't find how to do string formatting in Mojo in the docs. I have tried the common Python methods (str.format(), f-strings, % placeholder), but nothing worked out so far. I know Mojo is still a very young language, but I bet there is a way to do string formatting without manually adding strings together. Or not yet?

4 Answers 4

3

You can check the docs time to time, but as of right now there is only a bare bone implementation for strings.

In the mean time you can try to work around it via the python interoperability.

Sign up to request clarification or add additional context in comments.

Comments

1

For now Mojos's string formatting is not very advance, from online doc I can see some useful functions available which are __add__, __radd__. and __iadd__.

Sample code for __add__ that creates a string by appending another string at the end.

let a = String("test ").__add__("__add__")
# "test __add__"

Sample for __radd__ that creates a string by prepending another string to the start.

String("test ").__radd__("right add ")
# "right add test"

Sample for __iadd__ that appends another string to this string.

let a = String("test ")
let b = String("iadd")
a.__iadd__(b)
print(a)
# test iadd

Comments

1

In the interim period while official support for string formatting is not available, I have discovered a nice method through my exploration of vectors.

from python import Python
from collections.vector import DynamicVector


def fprint(template: String, vect: DynamicVector[String]):
    Python.add_to_path(".")
    let sf = Python.import_module("re")

    pattern = r'\{([^{}]*)\}'
    var matches = sf.findall(pattern, template)

    j = 0
    for i in matches:
        placeholder = String("")
                .join("{", i, "}")
        template = template.replace(placeholder, vect.__getitem__(j))
        j += 1
    
    print(template)

def main():
    var replacements = DynamicVector[String]()
    replacements.push_back("Alex")
    replacements.push_back("20")
    replacements.push_back("orange")

    let output = "hello my name is {name} and my age is {age},"
                    " my favorite color is {color}."
    fprint(output, replacements)

output:

mojo run main.mojo 
hello my name is Alex and my age is 20, my favorite color is orange.

Comments

0

Mojo now includes support for a limited subset of String.format(). For example:

    formatStr =  String("The {} is {}.")
    print(formatStr.format("sky", "blue"))
    print(formatStr.format("answer", 42))

As of Mojo 25.3 (May 2025) it only supports indexed placeholders ({} or {0}), and doesn't support format specifiers. For details, of what's currently supported, see: https://docs.modular.com/mojo/stdlib/collections/string/format/

This should continue to evolve with the rest of the standard library.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.