Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I have some problems converting data which I imported from a txt-file into proper Mathematica expressions. After importing my data looks like

sample = {"{3", "\"string1\"", 45, "\"string2\"", 8.32, " {2013", 8, 1, 0, 6, " 19}", "0.}"}

Now I would like to transform it into

converted = {3, "string1", 45, "string2", 8.32`, {2013, 8, 1, 0, 6, 19}, 0.}

I imported the file using Import[file.txt,"Data"]

share|improve this question
2  
If you provide a sample from file.txt we might be able to make Import do a part of the job for you. –  Pickett Feb 21 at 10:34
    
Try to import as "Package", not "Data" if you have a list written using Mathematica syntax. –  Szabolcs Feb 21 at 18:21
add comment

2 Answers

up vote 7 down vote accepted

You can Map with this:

ToExpression[StringJoin @@ Riffle[ToString /@ sample, ","]]
{3, "string1", 45, "string2", 8.32`, {2013, 8, 1, 0, 6, 19}, 0.`} 
share|improve this answer
    
Thanks for the elegant solution, solved my problem entirely –  RMMA Feb 21 at 11:19
    
@Kuba, Nice solution, but I wander: If this oddly shaped "sample" was imported from a text file, Wouldn't probably be better to parse the data correctly in the first instance, instead of correcting it afterwards? –  rhermans Feb 21 at 14:38
    
@rhermans That's what Pickett and Szabolcs are suggesting, I agree but OP has not responded to the comments. –  Kuba Feb 21 at 21:56
add comment

Another solution without the use of Riffle :

ToExpression@StringReplace[ToString[sample], {"\\" -> "", "{{" -> "{", "}}" -> "}"}]
share|improve this answer
1  
Congratulations on your fanatic badge :) (temporary message) –  Jacob Akkerboom Feb 25 at 17:28
1  
Thank you!(permanent message):-P –  tchronis Feb 25 at 18:05
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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