Home > Back-end >  change type of every element in array in julia
change type of every element in array in julia

Time:07-08

i want an array that contains a range of numbers but store them as strings. this is a sample output i need:

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

I tried this, but it produces a string with an array as its value.

julia> string([0:9...])
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"

so how can i generate such thing?

and this is how it can be done in python in case of better understanding:

>>> list('0123456789')
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

CodePudding user response:

First of all, note that Julia has separate types for Char (single characters) and String types. In Julia, ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] would be a character array, and can be created as:

julia> '0':'9'
'0':1:'9'

You can verify that this contains the above array by doing:

julia> '0':'9' |> collect |> print
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

But if you do want the result to be Strings and not Chars, you can use broadcasting to generate that:

julia> v = 1001:1010 # your input range here
1001:1010

julia> string.(v)
10-element Vector{String}:
 "1001"
 "1002"
 "1003"
 "1004"
 "1005"
 "1006"
 "1007"
 "1008"
 "1009"
 "1010"
  • Related