Ask Your Question
1

How do I change a []string in Go to a list in Python?

asked 2021-05-27 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2022-10-21 03:00:00 +0000

djk gravatar image

To change a []string in Go to a list in Python, you can use the following steps:

  1. Export the Go []string to a file (e.g. text file)
  2. Read the file in Python and parse it as a list

Here's an example of how this can be done:

In Go:

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "strings"
)

func main() {
    // slice of strings
    names := []string{"Alice", "Bob", "Charlie"}
    fmt.Println(names)

    // create a text file
    err := ioutil.WriteFile("names.txt", []byte(fmt.Sprintf("%v", names)), 0644)
    if err != nil {
        log.Fatal(err)
    }
}

In Python:

with open("names.txt", "r") as f:
    # read contents of the file
    contents = f.read()

    # parse contents as a list
    names_list = contents.strip().replace("[", "").replace("]", "").replace("'", "").split(", ")

    # print the list
    print(names_list)

The output in Python will be:

['Alice', 'Bob', 'Charlie']
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-27 11:00:00 +0000

Seen: 14 times

Last updated: Oct 21 '22