Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 857
Milliron X Avatar asked Jan 30 '20 23:01

Milliron X


1 Answers

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.

like image 80
Colin T Bowers Avatar answered Nov 09 '22 05:11

Colin T Bowers