merging certain list elements
You can useSequenceReplace
:
SequenceReplace[lis, {a__} /;
And @@ (StringContainsQ[{a}, Alternatives @@ CharacterRange["a", "z"]]) :>
StringJoin[a]]
% == res
True
Faster alternatives:
SequenceReplace[lis, {a__}/; Nor @@ StringFreeQ[_?LowerCaseQ] @ {a}:> StringJoin[a]]
and
StringJoin /@ Split[lis, Nor @@ StringFreeQ[_?LowerCaseQ] @ {##}&]
[Edit: Just noticed that @kglr was slightly faster in posting a very similar solution - I'll leave this here since it is at least slightly different, in that it merges arbitrarily many consecutive strings, while @kglr's solution only merges pairs]
You can use SequenceReplace
:
SequenceReplace[
lis,
{strs__?(StringContainsQ@CharacterRange["a", "z"])} :>
StringJoin@strs
]
(* {"ABC", "AbcDef", "1", "DEF", "GhiJkl", "MNO", "1,"} *)
Less elegant but fast solution:
lis //
{#, StringContainsQ[#, CharacterRange["a", "z"]]} & //
Transpose //
SplitBy[#, Last] & //
Map[ If[ Last@First@#, StringJoin@(#[[All, 1]]), Sequence @@ (#[[All, 1]]) ] &]