Search code examples
pythonjsontuplestwiliourllib

Separate python tuple with newlines


I am working on a simple script that collects earthquake data and sends me a text with the info. For some reason I am not able to get my data to be separated by new lines. Im sure I am missing something easy but Im still pretty new to programming so any help is greatly appreciated! Some of the script below:

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()

Solution

  • To split the tuple with newlines, you need to call the "\n".join() function. However, you need to first convert all of the elements in the tuple into strings.

    The following expression should work on a given tuple:

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

    Note that this is different from converting the entire tuple into a string. Instead, it iterates over the tuple and converts each element into its own string.