簡體   English   中英

我如何將.join()合並到python的此代碼中?

[英]how would i incorporate .join() in this code for python?

我在打印此代碼時試圖擺脫括號和逗號,但找不到我需要在哪里合並.join()以便將其刪除的地方。 我真的很想弄清楚這一點,因此,如果可以的話,請幫助我朝正確的方向發展,那將是很好的。 謝謝

def add(x, y):
    return x + y
def subtract(x, y):
    return x - y
def multiply(x, y):
    return x * y
def divide(x, y):
    return x / y

print ("Calculator: ")
print ("add : 1")
print ("subtraction: 2")
print ("multiply: 3")
print ("divide: 4")
foo = input("math solution: ")


num1 = float(raw_input("number 1: "))
num2 = float(raw_input("number 2: "))

if foo == 1:
    print (num1, "+", num2, "=", add(num1, num2)) 
elif foo == 2:
    print (num1, "-", num2, "=", subtract(num1, num2))
elif foo == 3:
    print (num1, "*", num2, "=", multiply(num1, num2))
elif foo == 4:
    print (num1, "/", num2, "=", divide(num1, num2))

您無需在代碼中合並.join() 只需從print語句中刪除括號即可,如下所示:

if foo == 1:
    print num1, "+", num2, "=", add(num1, num2))
elif foo == 2:
    print num1, "-", num2, "=", subtract(num1, num2)
elif foo == 3:
    print num1, "*", num2, "=", multiply(num1, num2)
elif foo == 4:
    print num1, "/", num2, "=", divide(num1, num2)

原因是在Python 2中,實際上並不像函數那樣調用print 添加括號時,您只是將數據打包到tuple (用逗號分隔的不可變的可迭代集合)。 然后, print語句將打印這些元組,而不是要打印的數據。

tl; dr從print語句中刪除括號,您無意中添加了破壞打印格式的數據包裝:)

而不是使用str.join ,您應該利用python的print 函數 為此,只需輸入:

from __future__ import print_function

在文件頂部(在模塊提示之后,如果存在)。 這將在python 2.6及更高版本上起作用(IIRC)。 您遇到的情況是,當您在python2.x上運行代碼時,

print (this, that, something_else)

被解釋為print 語句 ,然后解釋為要printtuple -因為元組用括號表示自己(字符串用引號表示自己),所以輸出中會出現不必要的括號和引號。 使用future語句啟用print函數會將其轉換為一個函數調用,該函數應該在python2.6 +和python3.x上做正確的事情。

您應該考慮使用sting格式。

在您的python版本中,您應該嘗試

print "%d + %d = %d" % (num1, num2, , add(num1, num2))

print "{0} + {1} = {2}".format(num1, num2, add(num1, num2))

前者可以工作,但后者(我認為)更漂亮,但僅適用於最新版本的Python。

暫無
暫無

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

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