Type conversions
Since StringReplace
works on lists, I would use:
List @@ StringExpression @@ StringReplace[
{"abc","def","2","ghi","7"},
n:NumberString :> ToExpression[n]
] //InputForm
{"abcdef", 2, "ghi", 7}
Here is a benchmark of the existing answers.
make = RandomChoice[{"abc", "def", "2", "ghi", "7"}, #] &;
bob[lis_] := (lis /. n_?(NumericQ[ToExpression[#]] &) :> ToExpression[n]) //. {s___,
str1_String, str2_String, f___} :> {s, str1 <> str2, f}
halirutan[lis_] :=
Module[{isNumber},
isNumber[s_String] := StringMatchQ[s, NumberString];
If[isNumber[#], ToExpression[#], #] & /@ StringJoin @@@ SplitBy[lis, isNumber]
]
hubble[list_] :=
Module[{res = StringJoin /@ Split[list, (LetterQ[#1] && LetterQ[#2]) &]},
Table[Which[DigitQ[res[[i]]], ToExpression[res[[i]]], True, res[[i]]], {i, 1,
Length[res]}]
]
carl[lis_] :=
List @@ StringExpression @@ StringReplace[lis, n : NumberString :> ToExpression[n]]
mrwiz2[lis_] :=
List @@ StringReplace[
StringRiffle[lis, "!"], {"!" -> "", d : DigitCharacter .. :> FromDigits[d]}]
Needs["GeneralUtilities`"]
BenchmarkPlot[{bob, halirutan, hubble, carl, mrwiz2}, make, 5]
If a string is a number can be tested by
isNumber[s_String] := StringMatchQ[s, NumberString]
and using a custom version of join that takes care if it is a list of numbers
join[s : {_?isNumber, ___}] := Sequence @@ ToExpression[s];
join[s_] := StringJoin[s];
you can apply SplitBy
to collect all non-numbers in your list and convert the rest to integers:
join /@ SplitBy[{"abc", "def", "2", "ghi", "7", "8", "jkl"}, isNumber]
(* {"abcdef", 2, "ghi", 7, 8, "jkl"} *)