Repeat string n times

I am looking to put a bunch of spaces in a formatted output in the nix language. To save space in the code I wanted to see if nix had a repeat string function.

In python, this would behave like the following:

str = 'Python program'
print(str*3)

output:

 Python programPython programPython program

There’s nothing builtin for this, but this works:

❯ nix repl -f '<nixpkgs>'
Welcome to Nix 2.15.1. Type :? for help.

Loading installable ''...
Added 19913 variables.
nix-repl> str = "Nix program"

nix-repl> lib.concatMapStrings (_: str) (lib.range 1 3)
"Nix programNix programNix program"
3 Likes

I would use replicate and concat, which makes the intent clearer:

nix-repl> lib.concatStrings (lib.replicate 3 "string")
"stringstringstring"
6 Likes

Oh nice, I forgot about replicate, even though I’m the one that merged the PR introducing it! :person_facepalming:

5 Likes

Btw @h7x4 created a PR to add lib.strings.replicateString: lib.strings: add `replicate` by h7x4 · Pull Request #261676 · NixOS/nixpkgs · GitHub