首页 > 解决方案 > 用换行符分隔 python 元组

问题描述

我正在编写一个简单的脚本来收集地震数据并向我发送包含信息的文本。出于某种原因,我无法让我的数据被新行分隔。我确定我错过了一些简单的东西,但我对编程还是很陌生,所以非常感谢任何帮助!下面的一些脚本:

import urllib.request
import json
from twilio.rest import Client
import twilio

events_list = []

def main():
  #Site to pull quake json data
  urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson" 
  
  webUrl = urllib.request.urlopen(urlData)
  
  if (webUrl.getcode() == 200):
    data = webUrl.read()

  # Use the json module to load the string data into a dictionary
    theJSON = json.loads(data)

  # collect the events that only have a magnitude greater than 4
    for i in theJSON["features"]:
      if i["properties"]["mag"] >= 4.0:
        events_list.append(("%2.1f" % i["properties"]["mag"], i["properties"]["place"]))

    print(events_list)
    
    # send with twilio
    body = events_list
    client = Client(account_sid, auth_token)
    if len(events_list) > 0:
      client.messages.create (
        body = body,
        to = my_phone_number,
        from_ = twilio_phone_number
      )
  else:
    print ("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))

if __name__ == "__main__":
  main()

标签: pythonjsontuplestwiliourllib

解决方案


要使用换行符拆分元组,您需要调用该"\n".join()函数。但是,您需要首先将元组中的所有元素转换为字符串。

以下表达式应该适用于给定的元组:

"\n".join(str(el) for el in mytuple)

请注意,这与将整个元组转换为字符串不同。相反,它遍历元组并将每个元素转换为自己的字符串。


推荐阅读