带有换行符的单独的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()

解决方法

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

以下表达式应在给定的元组上起作用:

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

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

,

由于您已将元组列表存储在“ events_list”中,因此您可以执行以下操作:

for event in events_list:
    print(event[0],event[1])

它会给你这样的东西:

4.12 10km near Florida
5.00 4km near Bay

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...