2

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

1 Answer 1

11

Use str.join:

waypoints = '|'.join("{0},{1}".format(p.latitude, p.longitude) for p in points)
Sign up to request clarification or add additional context in comments.

2 Comments

Also note the use of a generator expression (+1 btw). Never use a list comprehension when a generator expression works.
The join method on strings is one of the fastest ways to concatenate strings. @Dan Check out skymind.com/~ocrow/python_string for examples... and note that the naive concatenation with the + operator has terrible performance compared with str.join.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.