# How to convert a list of digits to a string in Mathematica

I want to convert a list of digits to a string, for example from {1,2,3,4,5}, I want to get the string 12345.

The following will work as long as the list does not begin with 0's:

{1, 2, 3, 4, 5} // FromDigits // ToString
Out[10]:= 12345

However if the list begins with 0's, as in

{0, 0, 1, 2, 3, 4} // FromDigits // ToString
Out[11]:= 1234

this method chops off the 0's in the front.

I could write a program that tests to see if the list begins with a string of 0's and then append that many zeros to the chopped off output, but I'd like a less procedural way of getting the string. Is this possible?

Note: the lists I want to convert are going to come from some prior computation, so unlike the above examples, I won't know their contents unless I explicitely examine them.

• Try StringRiffle[{0, 0, 1, 2, 3, 4}, ""] introduced in version 10.1
– Hans
Sep 2, 2018 at 1:47

Try

StringRiffle[{0, 0, 1, 2, 3, 4}, ""]
"001234"

Introduced in version 10.1 or in postfix as follows:

{0, 0, 1, 2, 3, 4} // StringRiffle[#, ""] &

While StringRiffle is nice and concise, but it has -- similar to many of the String-related tools in Mathematica -- severe performance issues. For example, the combination of IntegerString and StringJoin is ten times faster. Even roman465's somewhat creative solution to first convert the whole expression to a string and to remove the undesired parts afterwards is five times faster. If you can be be sure that only digits from 0 to 9 appear in the list, you can also use FromCharacterCode which is faster by almost two further orders of magnitude.

a = RandomInteger[{0, 9}, 100000];

s1 = StringRiffle[a, ""]; // RepeatedTiming // First
s2 = a // ToString // StringDelete[#, {"{", ", ", "}"}] &; // RepeatedTiming // First
s3 = StringJoin[IntegerString[a]]; // RepeatedTiming // First
s4 = FromCharacterCode[a + 48]; // RepeatedTiming // First
s1 == s2 == s3 == s4

0.311

0.0649

0.036

0.000534

True

It might be more convenient to convert your list to a string first, then remove unnecessary symbols.

{0, 0, 1, 2, 3, 4} // ToString // StringDelete[#, {"{", ", ", "}"}] &

"001234"

It can also be done in this way

StringJoin[ToString /@ {0, 0, 1, 2, 3, 4}]
• This feels like the most readable and syntactically correct to me. Sep 2, 2018 at 10:46
• @EmilioPisanty Thx. Sep 2, 2018 at 10:56

Using the three-argument form of IntegerString:

IntegerString[FromDigits @ #, 10, Length @ #] & @ {0, 0, 0, 0, 1, 2, 3, 4}

"00001234"