Message Boards Message Boards

0
|
981 Views
|
4 Replies
|
0 Total Likes
View groups...
Share
Share this post:

How to convert a list into a string of tab separated values

Posted 6 months ago

I have the list:

{
 {195, 0.81},
 {200, 0.33},
 {205, 0.68}
 }

from which I want to create the following string:

"195\t0.81\n200\t0.33\n205\t0.68"

I.e. convert the Wolfram syntax of a two columns table into a string of tab separated values.

Any idea for how to do that?

POSTED BY: Ehud Behar
4 Replies
Posted 6 months ago

You can do this very directly:

list = {{195, 0.81}, {200, 0.33}, {205, 0.68}};
ExportString[list, "TSV"]
(* "195\t0.81\n200\t0.33\n205\t0.68\n" *)

If you want to trim that trailing newline,

StringTrim[ExportString[list, "TSV"]]

Another option:

StringRiffle[list, "\n", "\t"]
POSTED BY: Eric Rimbey
Posted 6 months ago

Thanks very much! I wasn't aware of the StringRiffle[list, "\n", "\t"] approach.

A note: it seems that StringRiffle truncates digits after the decimal point:

StringRiffle[{{0.1, 0.12345678901}, {0.2, 0.12345678901}}, "\n", "\t"]
(*
0.1 0.123457
0.2 0.123457
*)

so I think I will use ExportString[{{0.1, 0.12345678901}, {0.2, 0.12345678901}}, "TSV"] instead.

POSTED BY: Ehud Behar

One way is to export to tsv format:

Export["~/Desktop/lst.tsv",
 {{195, 0.81}, {200, 0.33}, {205, 0.68}}]
Import["~/Desktop/lst.tsv", "Text"]// InputForm

You can also do it one step at a time:

{{195, 0.81}, {200, 0.33}, {205, 0.68}};
Map[ToString, %, {2}]
Map[Riffle[#, "\t"] &, %]
Riffle[%, "\n"]
% // Flatten
% // StringJoin // InputForm
POSTED BY: Gianluca Gorni
Posted 6 months ago

Thanks a lot! I think I am going to stick to Import["~/Desktop/lst.tsv", "Text"]// InputForm.

POSTED BY: Ehud Behar
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract