4
$\begingroup$

I have a string list consisting of alternating sequences of letters and digit characters. I would like to join the letter sequences and convert the digit characters into numbers composing a sublist of integers:

lis = {"a","bc","0","14","2","d","e","f","3","wx","z","r","st"}

I would like to obtain:

res = {{"abc"},{0,14,2},{"def"},{3},{"wxzrst"}}

Moving back and forth from symbols, numbers and string representation of digits makes for many lines of what must be extraneous code. I would be grateful for (and curious to see) ideas for economic code for this.

$\endgroup$
3
$\begingroup$
If[StringMatchQ[#[[1]], NumberString], FromDigits /@ #, {StringJoin@#}] & /@ 
 SplitBy[lis, StringMatchQ[NumberString]]

{{"abc"}, {0, 14, 2}, {"def"}, {3}, {"wxzrst"}}

or

SplitBy[If[StringMatchQ[#, NumberString], FromDigits@#, #] & /@ lis, Head] /.
 {s__String} :> {StringJoin@s}

{{"abc"}, {0, 14, 2}, {"def"}, {3}, {"wxzrst"}}

or

SequenceReplace[lis, 
  {{s__String?(Not@*StringMatchQ[NumberString] )} :> {StringJoin[s]} , 
  {n__String?(StringMatchQ[NumberString])} :> FromDigits /@ {n} } ]

   {{"abc"}, {0, 14, 2}, {"def"}, {3}, {"wxzrst"}}

$\endgroup$
5
$\begingroup$

Here's another variation similar to @kglr's:

SplitBy[
    List @@ StringExpression @@ StringReplace[lis, n:NumberString :> FromDigits[n]],
    Head
]

{{"abc"}, {0, 14, 2}, {"def"}, {3}, {"wxzrst"}}

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