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

2024-06-02 06:36:23 发布

您现在位置: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似乎会引起问题,而我为datetimes添加的格式会引起一些问题。你知道吗

我也想继续使用result{}字典-这里最好/最干净的解决方案是什么?你知道吗

编辑:为了澄清一点(刚刚了解了XY问题是什么),我正在尝试在pythonista上运行一些python代码。我在results{}中有我需要的信息,但是我需要将相同的打印值传递给一个字符串变量,这样我就可以在手机上使用它作为工作流的一部分。我想保持格式不变。你知道吗

clipboard.set(output_text)

我想我在这里要问的是什么是最干净的编码方式,因为我还用其他格式化方法/函数修改了结果{}的输出。你知道吗


Tags: 字符串datetimetime格式status世界trainresult
3条回答

是的,有一种方法可以用三个引号''''''赋值给一个变量,下面的例子

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']))

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

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)

输出:

Train number: 192
Destination: Wigan
Estimated arrival at Feltham: 12:23
Time now: 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()

相关问题 更多 >