4
$\begingroup$

Considering a list:

lst = {"1", "2", "3", "4", "5", "6"}

How can I have two strings :

str1 = "1, 2, 3"
str2 = "4, 5, 6"

Thanks!

$\endgroup$
  • $\begingroup$ str1 = StringJoin @@ lst[[ ;; 3]] $\endgroup$ – C. E. Apr 15 '15 at 12:01
3
$\begingroup$
 StringTake[ToString@#, {2, -2}] & /@ Partition[lst, 3]
{"1, 2, 3", 
 "4, 5, 6"} 
$\endgroup$
4
$\begingroup$

Assuming you always want strings with 3 items:

Map[StringJoin @@ Riffle[#, ", "] &, Partition[Map[ToString, lst], 3]]
$\endgroup$
3
$\begingroup$

This is very similar to your previous question and so is the solution:

lst = {"1", "2", "3", "4", "5", "6"}

ToString @ Row[#, ", "] & /@ Partition[lst, 3]
{"1, 2, 3", "4, 5, 6"}
$\endgroup$
3
$\begingroup$
lst = {"1", "2", "3", "4", "5", "6"};
Developer`PartitionMap[StringTrim[ToString@#, "{" | "}"] &, lst, 3]
(* {"1, 2, 3", "4, 5, 6"} *)
$\endgroup$
3
$\begingroup$

This gives exactly the output you wrote down:

str1 = StringDrop[StringDrop[ToString@Partition[lst, 3][[1]], 1], -1]
str2 = StringDrop[StringDrop[ToString@Partition[lst, 3][[2]], 1], -1]

Could be made more elegant of course, and more flexible.


EDIT to make it more elegant:

TableForm[StringJoin /@ Partition[lst, 3]]

for display without the commas.

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