繁体   English   中英

使用字典将打印输出转换为python中的字符串

[英]Converting printed outputs using a dictionary to a string in python

我是Python的新手,并希望能够回答我的问题。 我有以下打印输出,它将输出值到控制台。

# Print out the train results.
print("-" * 20)
print("Train number: " + str(result['trainNumber']))
print("Destination: " + str(result['locationName']))
print("Departing at: " + str(result['departure_time']))
print("Platform: " + str(result['platform']))
print("Status: " + str(result['Status']))
print("Operator: " + str(result['operator']))
print("Estimated arrival at Feltham: " + result['ETA'].strftime("%H:%M")) # Format ETA as H:M
print ("Time now: " + str(datetime.datetime.now().strftime("%H:%M")))
print("Time until train: " + str(int(result['timeToTrain'])) + " minutes")
print("Chance of getting this train: " + result['chance'])

但是,我想将这些转换为单个多行字符串以作为变量传递。 这可能吗? 我不确定如何处理新行 - \\ n似乎会导致问题,而且我为日期时间添加的格式会引起一些问题。

我想继续使用结果{}字典 - 这里最好/最干净的解决方案是什么?

编辑:为了澄清一点(刚刚了解到XY问题是什么),我试图在pythonista上运行一些python代码。 我在结果{}中有我需要的信息,但我需要将相同的打印值传递给单个字符串变量,以便我可以将其用作手机工作流程的一部分。 我想保持格式相同。

clipboard.set(output_text)

我想我在这里问的是最简洁的编码方式是什么,因为我也在使用其他格式化方法/函数修改结果{}的输出。

您可以创建一个格式字符串,用于查找字典中的值:

format_string = ('Train number: {trainNumber}\n'
                 'Destination: {locationName}\n'  # etc
                 'Estimated arrival at Feltham: {ETA:%H:%M}\n'
                 'Time now: {now:%H:%M}\n')  # etc

用法:

from datetime import datetime

result = {'trainNumber': 192,
          'locationName': 'Wigan',
          'ETA': datetime(2017, 9, 4, 12, 23)}

print format_string.format(now=datetime.now(),
                           **result)

输出:

火车数量:192
目的地:威根
估计抵达费尔特姆:12:23
现在时间:11:38

只需使用+来连接字符串。 此外,datetime.datetime.now()。strftime(“%H:%M”))已经是一个字符串,因此不需要str。

import pyperclip

pyperclip.copy(("-" * 20) + "\nTrain number: " + str(result['trainNumber'])   
+ "\nDestination: " + str(result['locationName']))
clipboard = pyperclip.paste()

是的,有一种方法可以使用三引号“”“”分配给变量,例如下面的例子

var = """
{0}
Train number: {1}
Destination: {2}
Departing at: {3}
Platform: {4}
Status: {5}""".format(("-"*20),str(result['trainNumber']),str(result['locationName']),
str(result['departure_time']), str(result['platform']), str(result['Status']))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM