2
$\begingroup$

Considering we have an array:

a = {2/3, 4/5, 9/7, 3/7, 1/7, 1/9};

How can I get this to be:

"2/3 4/5 9/7 3/7 1/7 1/9"

Thanks!

$\endgroup$
1

5 Answers 5

6
$\begingroup$

I would love this to be uniform for both integer and rational numbers

a2 = {2/3, 4/5, 9/7, 3/7, 1.5, 3, 1/9};


StringTrim@StringJoin[" " <> ToString[#, InputForm] & /@ a2]
(* 2/3 4/5 9/7 3/7 1.5 3 1/9 *)

Row[ToString[#, InputForm] & /@ a2, "  "]
(* 2/3  4/5  9/7  3/7  1.5  3  1/9 *)

StringReplace[ToString[a, InputForm], {"{" | "}" -> "", "," -> " "}]
(* 2/3  4/5  9/7  3/7  1.5  3  1/9 *)

StringJoin[Riffle[ToString[#, InputForm] & /@ a2, " "]]
(* 2/3 4/5 9/7 3/7 1.5 3 1/9 *)
$\endgroup$
4
$\begingroup$

Or

StringTake[ToString[a, FormatType -> InputForm], {2, -2}]

The inelegant use of StringTake strips off the leading and trailing brackets.

$\endgroup$
4
  • $\begingroup$ Elegant! You can use StringDelete[..., "{" | "}" | ","] instead of StringTake. $\endgroup$ Apr 12, 2015 at 10:29
  • 1
    $\begingroup$ Nice. Btw, this does not give the same form the OP wanted due the "," being there between the numbers. May be just need small modification? $\endgroup$
    – Nasser
    Apr 12, 2015 at 10:51
  • $\begingroup$ May be just need small modification? -- Surely, but left as an exercise for the reader :-) $\endgroup$ Apr 12, 2015 at 11:46
  • 1
    $\begingroup$ Nice to see you here @HighPerformanceMark ! :-) $\endgroup$
    – Mr.Wizard
    Apr 12, 2015 at 16:47
2
$\begingroup$

Terse:

a = {1, 17, 2/3, 4/5, 9/7, 3/7, 1/7, 1/9};

ToString @ Row[InputForm /@ a, " "]
"1 17 2/3 4/5 9/7 3/7 1/7 1/9"
$\endgroup$
2
$\begingroup$

Yet another possibility:

a = {2/3, 4/5, 9/7, 3/7, 1/7, 1/9, 5, 6, 99/10};
ExportString[{a}, "Table", "FieldSeparators" -> " "]
   "2/3 4/5 9/7 3/7 1/7 1/9 5 6 99/10"
$\endgroup$
2
$\begingroup$
a = {2/3, 4/5, 9/7, 3/7, 1/7, 1/9};
StringJoin@Cases[a, Rational[x_, y_] :> 
   " "<>ToString[x] <> "/" <> ToString[y]]

Mathematica graphics


Reply to comment "I would love this to be uniform for both integer and rational numbers":

a = {2/3, 4/5, 9/7, 3/7, 1/7, 1/9, 5, 6, 99/10};
f[Rational[x_, y_]] := " " <> ToString[x] <> "/" <> ToString[y];
f[x_] := " " <> ToString[x];
StringJoin[f[#] & /@ a]

Mathematica graphics

$\endgroup$
1
  • $\begingroup$ I would love this to be uniform for both integer and rational numbers. Thanks! $\endgroup$
    – SuTron
    Apr 12, 2015 at 10:00

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.