4
$\begingroup$

I have generated a string list

"      1      1   3212    8.0000       75  61   1  74  3   58      0.0000"

I want to convert them into real numbers however, when I write

ToExpression["      1      1   3212    8.0000       75  61   1  74  3   58      0.0000"]

I get 0., which is not so pleasing.

further when I enter

    ToExpression["      1      1   3212    8.0000       75  61   1  74  3   58      0.0000",InputForm,Hold]

I get

Hold[3212 8. 75 61 74 3 58 0.]

Where the two 1 has been lost.

Therefore I am here asking for help.

$\endgroup$
  • $\begingroup$ closely related: 8938 $\endgroup$ – Kuba Jul 7 '17 at 9:17
  • $\begingroup$ A space between the numbers is implicit multiplication. Furthermore, at (I believe) parsing time (if you input Hold[1 2] directly, the 1 is retained) the 1s in the multiplication expression are considered redundant and dropped from the result. If you look closely, actually three ones have been lost. $\endgroup$ – LLlAMnYP Jul 7 '17 at 9:33
7
$\begingroup$
s = "      1      1   3212    8.0000       75  61   1  74  3   58      0.0000";
ImportString[s, "Table"]

Or using ReadList:

str = StringToStream[s];
list = ReadList[str, Number(*, RecordLists -> True*)];
Close[str];
list
$\endgroup$
  • 1
    $\begingroup$ nice, probably the most efficient way of converting strings to numbers. $\endgroup$ – LLlAMnYP Jul 7 '17 at 9:35
6
$\begingroup$
ToExpression[StringSplit["      1      1   3212    8.0000       75  61   1  74  3   58      0.0000"]]
$\endgroup$
6
$\begingroup$
str = "      1      1   3212    8.0000       75  61   1  74  3   58      0.0000";

StringCases[str, x : NumberString :> ToExpression[x]]

{1, 1, 3212, 8., 75, 61, 1, 74, 3, 58, 0.}

$\endgroup$
3
$\begingroup$
str = "      1      1   3212    8.0000       75  61   1  74  3   58   0.0000";

Rest @ Interpreter[DelimitedSequence["Number"]][str]

{1, 1, 3212, 8., 75, 61, 1, 74, 3, 58, 0.}

$\endgroup$
2
$\begingroup$

Actually, you had the right idea:

r = ToExpression[
    "      1      1   3212    8.0000       75  61   1  74  3   58      0.0000",
    InputForm,
    Hold
]
r //FullForm

(*
Hold[3212 8. 75 61 74 3 58 0.]

Hold[Times[1,1,3212,8.`,75,61,1,74,3,58,0.`]]
*)

The formatted output (in StandardForm) does not show "superfluous" unit multiplicands. However, they are still there when you look at the FullForm

$\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.