2
$\begingroup$

Consider some string parameters: Par1, Par2, Par3. Could you please tell me how to compose a filename string of the form:

filename="experiment-Par1_number-Par2_position-Par3.dat"

For the data: e.g.,

Par1="Exp";
Par2="11";
Par3="End";

the filename would be:

filename="experiment-Exp_number-11_position-End.dat"
$\endgroup$

3 Answers 3

2
$\begingroup$

Using StringForm:

pars = {"Exp", "11", "End"};

fmtString = "experiment-``_number-``_position-``.dat";

filename = ToString@StringForm[fmtString, Sequence @@ pars]

"experiment-Exp_number-11_position-End.dat"

$\endgroup$
2
  • 1
    $\begingroup$ Note that the result of StringForm is not a string and thus not usable as file name for Import/Export etc. For those cases, you either need to apply ToString or use StringTemplate instead $\endgroup$
    – Lukas Lang
    Commented Nov 1, 2022 at 19:00
  • $\begingroup$ Thanks @LukasLang for the correction. $\endgroup$
    – Syed
    Commented Nov 1, 2022 at 19:05
3
$\begingroup$

Using StringJoin

par1 = "Exp";
par2 = "11";
par3 = "End";
filename =  "experiment-" <> par1 <> "_number-" <> par2 <> "_position-" <> par3 <> ".dat"

(* "experiment-Exp_number-11_position-End.dat" *)
$\endgroup$
3
$\begingroup$

I actually like StringTemplate for these kinds of things. It's nicely reusable as a function, like a curried StringForm (but it produces actual strings at the end). You also have the option of naming the template slots

filenameTemplate = StringTemplate["experiment-``_number-``_position-``.dat"];
filename = filenameTemplate["Exp", 11, "End"]

or

filenameTemplate = 
  StringTemplate["experiment-`experiment`_number-`number`_position-`position`.dat"];
filename = filenameTemplate[<|"experiment" -> "Exp", "number" -> 11, "position" -> "End"|>]
$\endgroup$
1
  • $\begingroup$ Without knowing it I have been using a lot of templates for file names but never used StringTemplate. This will greatly tidy up my codebase and make things more legible $\endgroup$ Commented Nov 2, 2022 at 0:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.