簡體   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