1
$\begingroup$

Using the for loop how can I print:

file0.jpg
file1.jpg
file2.jpg
file3.jpg
file4.jpg
file5.jpg
file6.jpg
file7.jpg
file8.jpg
file9.jpg

The closest code I came up with is:

For[n = 0, n <= 9, n++, Print[file : n .jpg]]

Obviously this will print above with extra extra : which is not what I want.

In Python this is easily done by formatting [a place holder]:

for x in range(10):
    print("file{}.jpg".format(x))

How do you do this in Mathematica?

$\endgroup$
  • $\begingroup$ Take a look in the documentation at ToString, at the string concatenation operator <>, and e.g. at Table as an alternative for your looping construct. $\endgroup$ – MarcoB Feb 25 '16 at 13:15
2
$\begingroup$

You can do this,

"file" <> IntegerString[#] <> ".jpg\n" & /@ Range[0, 9] // StringJoin

or this

Print["file" <> IntegerString[#] <> ".jpg"] & /@ Range[0, 9]

or this

Do[Print["file" <> IntegerString[n] <> ".jpg"], {n, 0, 9}]

or this

For[n = 0, n < 10, n++, Print["file" <> IntegerString[n] <> ".jpg"]]
| improve this answer | |
$\endgroup$
1
$\begingroup$

StringForm is very similar to printf (which is very similar to Python's string formatting functions):

For[n = 0, n <= 9, n++, Print[StringForm["file``.jpg", n]]]

The double backquotes serve as the placeholder for the subsequent strings or stringified expressions to insert. If you want to use more than one extra argument, then put an index between your backquotes, going from 1 to the number of other expressions you are passing to StringForm.

EDIT: StringForm outputs a "plaintext" format. To get an actual string you should wrap it in "ToString":

For[n = 0, n <= 9, n++, Print[ToString[StringForm["file``.jpg", n]]]]

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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