6
$\begingroup$

I have a list:

lis = {"20","ab","Cd","10","E"}

in which I would like to join adjacent elements if they are letters and not digits, to give:

res = {"20","abCd","10","E"}

Again thanks for any help!

$\endgroup$

4 Answers 4

7
$\begingroup$

Maybe something like this:

StringJoin /@ SplitBy[lis, LetterQ]

Edit

That doesn't work if there are adjacent non-letter strings. Try this instead:

If[AllTrue[#, LetterQ], StringJoin[#], Splice[#]] & /@ SplitBy[lis, LetterQ]

Another option:

Flatten[SequenceSplit[lis, {str__?LetterQ} :> StringJoin[str]]]
$\endgroup$
1
  • $\begingroup$ Works well. Thanks! $\endgroup$
    – Suite401
    Commented Aug 31, 2022 at 2:41
4
$\begingroup$
lis = {"20", "ab", "Cd", "10", "E"}

Using SequenceReplace:

SequenceReplace[lis, {s__String?(StringFreeQ[DigitCharacter])} .. :> 
  StringJoin@s]

{"20", "abCd", "10", "E"}

$\endgroup$
3
$\begingroup$
list = {"20", "ab", "Cd", "bb", "10", "33", "E", "F"};

Using ReplaceRepeated

list //. {a___, b_?LetterQ, c_?LetterQ, d___} :> {a, StringJoin[b, c],d}

{"20", "abCdbb", "10", "33", "EF"}

$\endgroup$
2
$\begingroup$
list = {"20", "ab", "Cd", "bb", "10", "33", "E", "F"};

Grabbing the @eldo's list and using ReplacePart and DeleteElements:

p = Split[Position[list, s_String /; LetterQ[s]], #2[[1]] - #1[[1]] == 1 &];

f = DeleteElements[ReplacePart[list, Thread[p -> #]], Length /@ p - 1 -> #] &;

f@Map[StringJoin, Extract[list, List@*Span @@@ MinMax /@ p]]

{"20", "abCdbb", "10", "33", "EF"}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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