Milliron X
Milliron X

Reputation: 1213

Convert an integer array to string array in Julia

Is there a way to convert an array of integers (or any numbers) to an array of strings in Julia? Essentially, I want to convert [1 2 3 4] to ["1" "2" "3" "4"].

Stuff that doesn't work:

numbers = [1 2 3 4];
strings = ["1" "2" "3" "4"];
string(numbers)
convert(Array{String}, numbers)

Output:

"[1 2 3 4]"
ERROR: MethodError: Cannot `convert` an object of type Int64 to an object of type String
...

I'm using Juila 1.3.1

Upvotes: 6

Views: 3329

Answers (1)

Colin T Bowers
Colin T Bowers

Reputation: 18530

Surprisingly, this doesn't appear to be a duplicate.

For a single number, you use the string function. For an array of numbers, you need to broadcast the string function to each element of the array. The simplest way to do this in Julia is using the . syntax, e.g.:

x = [1,2,3,4]
y = string.(x)

Note, broadcasting works for any function (including user-defined functions). So, e.g.:

f(x) = x^2
f.([1,2,3,4])

just works.

Upvotes: 9

Related Questions