I have this segment of code to extract the shortest path in a graph from one node to another
g = json_graph.node_link_graph(json.load(open("MPLS-topo.json")))
paths = nx.shortest_path(g, "H1", weight="weight")
for dest in paths.keys(): # Nicely output all those paths
if dest == "H2":
print "Shortest Path from H1 to {} is:".format(dest)
print "{}".format(paths[dest])
the output of it is
Shortest Path from H1 to H2 is:
['H1', u'S1', u'S2', u'S3', u'S5', u'H2']
I want to remove u and convert the path to string like this
H1-S1-S2-S3-S5-H2
I tried this
path = [s.replace('u', '') for s in paths[dest]]
print path
y = "-".join(path)
but it gives me the same output. How can I do this in python?
Please try encode option which will convert unicode into string format:
path = [s.encode('utf-8') for s in li]
print("-".join(path))
This should give you the desired output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.