Why does Julia think a vector is a string?

You can also evaluate arbitrary expressions from strings in the global scope, with e.g.:

include_string(Main, "[1,2,3]")

or

eval(Meta.parse(["1,2,3"]))

But it is not the recommended way to go. For instance, this cannot be done locally inside a function. @mzaffalon’s proposal is better, although not applicable to arbitrary strings.

That appears to work! I wish you’d seen the question when I first asked it! It would have saved me a week’s time!

It now works perfectly! How can I ever thank you enough!

Your suggestion: parse.(Int, split(strip(str, ['[', ']']), ',’))
works, but the resulting vector has spaces between each element, eg, [1, 2, 3].
To save space, I’d prefer [1,2,3]. How do I modify the parse expression to avoid the spaces?

What do you mean by “the vector has spaces”? Whether or not there are spaces is just a printing/display issue, the underlying vectors are the same irrespective of the whitespace between elements:

julia> [1, 2, 3] == [1,2,3] == [1  ,   2   ,   3]
true
2 Likes

Here’s an example:

julia> empty!(S)
Stack{Any}(Deque [Any])

julia> s = “[1,2,3]”
“[1,2,3]”

julia> push!(S,s)
Stack{Any}(Deque [Any[“[1,2,3]”]])

julia> t = parse.(Int, split(strip(s, [‘[’,‘]’]),‘,’))
3-element Vector{Int64}:
1
2
3

julia> push!(S,t)
Stack{Any}(Deque [Any[“[1,2,3]”, [1, 2, 3]]])

Notice the difference between pushing s and pushing t. I’d like to get rid of those spaces in t.

There are no spaces in a vector. It’s just how Julia prints vectors in some cases. There is no way to remove it, because it doesn’t exist.

(I mean, you can remove it from the printing, in principle, but it’s not really there in the vector itself.)

3 Likes

But again this is just a display issue, there are no “spaces” in the actual object [1, 2, 3], which is just a Vector{Int64}, which by default gets displayed in the way you show when not displayed on its own:

julia> [[1, 2, 3]]
1-element Vector{Vector{Int64}}:
 [1, 2, 3]

I guess you could overwrite the show methods for this if it bothers you?

OK, thanks for the explanation.

What space do you want to save?

Can you tell us what you are trying to achieve?

How can I remove them from the printing?

I’m trying to achieve a denser printout: [1,2,3] rather than [1, 2, 3].

You’re confusing strings and arrays. You have an array with mixed elements:

The first element is a printed representation of a string ("[1,2,3]"), the latter is a printed representation of an array ([1, 2, 3] or

[1,         2,          3]

doesn’t matter, as it’s just how julia prints the array to the screen).


Please enclose your code in triple backticks when posting to make it easier for people to read it and follow along. This makes it easier for use to help you.

2 Likes

OK, thanks for the explanation.