Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Building a string from a loop

Tags:

python

string

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

like image 411
Dan Avatar asked Feb 22 '26 23:02

Dan


1 Answers

Use str.join:

waypoints = '|'.join("{0},{1}".format(p.latitude, p.longitude) for p in points)
like image 184
Mark Byers Avatar answered Feb 25 '26 13:02

Mark Byers