如何解决带有换行符的单独的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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。