Python - 从循环构建字符串
我有一组点,这些点有经度和纬度的数值,我想创建一个特定格式的字符串,以便能和Gmaps API一起使用:
LatitudeX,LongitudeX|LatitudeY,LongitudeY
这个最终的字符串会由不确定数量的经纬度对组成。
我之前主要用PHP编程,虽然我已经搞出了一个能用的东西,但感觉有点笨重。我在想有没有更“Python风格”的方法来实现这个结果。
这是我目前的代码:
waypoints = ''
for point in points:
waypoints = waypoints+"%s,%s" % (point.latitude, point.longitude)+"|"
waypoints = waypoints[:-1]
任何建议都很感谢。
谢谢
1 个回答
11
使用 str.join
方法:
waypoints = '|'.join("{0},{1}".format(p.latitude, p.longitude) for p in points)