How to do string interpolation (formatting) with Mojo?

730 views Asked by At

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?

3

There are 3 answers

0
Károly Szabó On

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.

0
abdullahselek On

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
0
Denis Tu On

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.