簡體   English   中英

如何在Python的同一行上打印來自不同函數的兩個語句

[英]How to print two statements from different functions on the same line in Python

我試圖在Python 2.7(或3.4)的同一行上打印兩個輸出語句。 打印語句不會一個接一個地出現,例如print a / print b。 我的程序使用329(例如),然后以字為單位返回該值-三百二十九。 因此,它將確定300個零件並打印,然后確定29個零件並打印。

if (main == hundreds[index]):
    print hundreds_words[index]
for location in range (0, 10):
    if (difference == twenties[location]):
        print twenties_words[location]

我想將29與300印刷在同一行上。 我想我可以嘗試建立一個解決方案,但我想知道Python是否具有執行此操作的過程。

是的,它確實。 您只需要告訴print不要在第一行之后添加新行。 在python2中,您可以通過添加結尾逗號來實現此目的: print mystring, 在python3中, print是具有end關鍵字參數的函數: print(mystring, end="")

簡單的方法是重寫您的數字轉單詞功能,並使其返回一個字符串而不是打印它。

更復雜的方法是重定向stdout以將print輸出捕獲為字符串。

編輯:看起來我使它變得比必要的更為復雜; 你可以嘗試

output_words = []
if (main == hundreds[index]):
    output_words.append(hundreds_words[index])
for location in range (0, 10):
    if (difference == twenties[location]):
        output_words.append(twenties_words[location])
return " ".join(output_words)

在python 2中,您可以使用結束print語句,以指示不以換行符終止,例如:

print hundreds_words[index], 

在python 3(或py2 from __future__ import print_function )中,您需要顯式定義end ,例如:

print(hundreds_words[index], end=' ')

但是理想情況下,您只需要將所有結果收集到一個list ,然后在最后join()即可。

result = []
if (main == hundreds[index]):
    result.append(hundreds_words[index])
for location in range (0, 10):
    if (difference == twenties[location]):
        result.append(twenties_words[location])

print(' '.join(result))

始終設計函數以返回值,而不是打印它們(這是更多的Pythonic!)。 因此,您應該以這種方式修改代碼:

# FOR PYTHON 2.x

if (main == hundreds[index]):
    print hundreds_words[index], # Note the comma
for location in range (0, 10):
    if (difference == twenties[location]):
        print twenties_words[location]

# FOR PYTHON 3.x

if (main == hundreds[index]):
    print(hundreds_words[index], end=" ") # end=" " will override the default '\n' and leave a space after the string
for location in range (0, 10):
    if (difference == twenties[location]):
        print(twenties_words[location])

還有第三個選項,更具可伸縮性: 所有數據包裝在列表中,然后打印所有內容。

printable = []

if (main == hundreds[index]):
    printable += hundreds_words[index]
for location in range (0, 10):
    if (difference == twenties[location]):
        printable += twenties_words[location]

print(" ".join(printable))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM