Hi:
I need to pass an array to a Python script through a Port where the values in array are quoted. So, how do I convert
[1,2,3,4]
to
"[1,2,3,4]"
Thanks!
gani-
Hi:
I need to pass an array to a Python script through a Port where the values in array are quoted. So, how do I convert
[1,2,3,4]
to
"[1,2,3,4]"
Thanks!
gani-
Perhaps this?
iex> inspect [1,2,3,4]
"[1, 2, 3, 4]"
Yes, that works! I just found another way in the documentation which is more convoluted but works just the same.
p1 = press = 0..10 |> Enum.to_list()
p2= Macro.to_string(quote do: unquote(p1))
#=> "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
You could also use Jason.encode!
iex(8)> Jason.encode!([1, 2, 3, 4])
"[1,2,3,4]"
It might also help with code readability.
You will need to add it to your mix.exs file if it isn’t already included
defp deps do
[
{:jason, "~> 1.2"}
]
end
I’d strongly suggest using a data format known to both the elixir and the python side – like json. Inspect converts terms to a string representation in elixir syntax. This is not meant to work with python (even if it might in some places).
Thanks!
gani-
I’ve had great success using this module with python ports: GitHub - okeuday/erlang_py: Erlang External Term Format for Python
Here’s another one:
iex> "[#{Enum.join([1,2,3,4], ",")}]"
"[1,2,3,4]
Or you could pass it as an iolist:
iex> IO.puts ["[", Enum.join([1,2,3,4], ","), "]"]
[1,2,3,4]
Actually, I’m not sure now if you actually want to include the "
or whether you just wanted a string representing an array.
Until you do:
iex> inspect [100, 101, 102]
"'def'"
Personally, I’d use one of the more formal, established approaches for coaxing data across the Elixir/Python divide, such as JSON or Erlang_py discussed above. The corner cases have been sorted so you don’t have to.
FWIW - You can fix the inspect
approach with the charlists option:
iex(5)> inspect [100, 101, 102], charlists: :as_lists
"[100, 101, 102]"
Thank you!