Dan
Dan

Reputation: 6553

Python - Building a string from a loop

I have a set of points that have latitude and longitude values and I am trying to create a string in the following format in order to work with the Gmaps API:

 LatitudeX,LongitudeX|LatitudeY,LongitudeY

The final string will be built using an unknown number of lat long pairs.

My previous experience is with PHP and, whilst I have managed to get something working however, it seems a bit clumsy and I was wondering if there as a more 'pythonic' way to achieve the result.

Here's what I have so far:

 waypoints = ''

 for point in points:
     waypoints = waypoints+"%s,%s" % (point.latitude, point.longitude)+"|"

 waypoints = waypoints[:-1]

Any advice appreciated.

Thanks

Upvotes: 2

Views: 4118

Answers (1)

Mark Byers
Mark Byers

Reputation: 838036

Use str.join:

waypoints = '|'.join("{0},{1}".format(p.latitude, p.longitude) for p in points)

Upvotes: 11

Related Questions