7
$\begingroup$

in this expression = "{1 2 3 4 5 6 7 8}", I want to replace each space by a comma , to get {1,2,3,4,5,6,7,8}.

$\endgroup$
  • $\begingroup$ Try this. expression = "{1 2 3 4 5 6 7 8}"; ToExpression@StringSplit[ StringReplace[expression, "{" | "}" -> ""]] $\endgroup$ – PlatoManiac Dec 16 '15 at 6:47
  • $\begingroup$ @PlatoManiac, thanks for your answer! $\endgroup$ – BetterEnglish Dec 16 '15 at 7:00
  • $\begingroup$ related: 50403 $\endgroup$ – Kuba Dec 16 '15 at 7:06
  • $\begingroup$ ImportString[StringReplace["{1 2 3 4 5 6 7 8}", "{" | "}" -> ""], "List", "LineSeparators" -> " "] $\endgroup$ – J. M. will be back soon Dec 16 '15 at 7:12
11
$\begingroup$
expression = "{1 2 3 4 5 6 7 8}";

A few alternatives to PlatoManiac's approach:

ToExpression[
    expression, 
    StandardForm, 
    Function[e, Sequence @@@ Unevaluated[e], HoldAll]
]

or

ToExpression @ StringReplace[expression, " " -> ","]
{1, 2, 3, 4, 5, 6, 7, 8} 

or

 StringCases[expression, n : NumberString :> ToExpression[n]]

 ToExpression @ StringCases[expression, NumberString]
$\endgroup$
7
$\begingroup$

A possibility with WhitespaceCharacter

ToExpression@
     StringReplace[expression, WhitespaceCharacter -> ","]

(* {1, 2, 3, 4, 5, 6, 7, 8} *)

Another using Interpreter

Interpreter[
   DelimitedSequence["Integer", {"{", " ", "}"}]][expression]
$\endgroup$
6
$\begingroup$

My thought was to drop the brackets using StringTake and then import it using ImportString

"{1 2 3 4 5 6 7 8}"~StringTake~{2, -2}~ImportString~"Table" // First
(* {1, 2, 3, 4, 5, 6, 7, 8} *)

edit I just realized this is very similar to what J.M. suggested in his comment (although I'm playing around with infix notation here).

$\endgroup$
  • 1
    $\begingroup$ It's not so similar to JMs version and in fact, I was going to post exactly this solution, because I think it is noteworthy that a space-separated list of numbers can be imported as "Table". +1 $\endgroup$ – halirutan Dec 16 '15 at 8:39
  • $\begingroup$ Thanks, it was my first thought since I'm regularly running python (or c or fortran) code that outputs a big list or matrix and the quickest way for me to plot it is to just copy it and paste it into an ImportString command. $\endgroup$ – Jason B. Dec 16 '15 at 8:47
4
$\begingroup$

Since space is implicit Times similar methods to Convert head Times to List can be applied:

Block[{Times = List}, ToExpression @ "{1 2 3 4 5 6 7 8}"] // First
{1, 2, 3, 4, 5, 6, 7, 8}

Though in this case a much shorter method works too:

ToHeldExpression[expression] ~Level~ {3}
{1, 2, 3, 4, 5, 6, 7, 8}
$\endgroup$
3
$\begingroup$

Another solution, inspired by Kuba's first one:

Sequence @@@ ToExpression[expression, StandardForm, Inactivate] 
$\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.