Skip to main content
 首页 » 编程设计

Python之从循环构建字符串

2025年05月04日22cyq1162

我有一组具有纬度和经度值的点,我正在尝试创建以下格式的字符串以便使用 Gmaps API:

 LatitudeX,LongitudeX|LatitudeY,LongitudeY 

最终的字符串将使用未知数量的经纬对构建。

我以前的经验是使用 PHP,虽然我已经设法让一些东西工作,但是它看起来有点笨拙,我想知道是否有更“pythonic”的方式来实现结果。

这是我目前所拥有的:

 waypoints = '' 
 
 for point in points: 
     waypoints = waypoints+"%s,%s" % (point.latitude, point.longitude)+"|" 
 
 waypoints = waypoints[:-1] 

感谢任何建议。

谢谢

请您参考如下方法:

使用str.join :

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