2012-08-02 47 views
0

我需要做一個python測驗。如何解決這個Python字符串插值相關?

這裏是問題:

Your challenge here is to write a function format_point that returns a string representing a point in 2-space. The function takes three parameters. The first two are floating point numbers representing the x and y coordinates of a point and the third parameter is an integer specifying the required number of digits after the decimal point. The returned string is of the form "(23.176, 19.235)". For example, the following three lines of code should print the output (0.67, 17.12).

我所做的是:

>>> def coordinate(x,y,n): 
...  str_x = format(x,"."+n+"f") 
...  str_y = format(y,"."+n+"f") 
...  print("("+str_x+","+str_y+")") 
... 
>>> coordinate(10.242,53.124,2) 

我得到了錯誤:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in coordinate 
TypeError: cannot concatenate 'str' and 'int' objects 

我哪裏做錯了?

+0

由於這看起來像功課,我不會給出答案,但檢查出型鑄造在[Python中(HTTP:// docs.python.org/library/functions.html#str)。 – adchilds 2012-08-02 02:44:08

+0

查看字符串格式化它的典型'「」。格式(arg1,arg2,...)' – 2012-08-02 02:54:25

回答

3

cannot concatenate 'str' and 'int' objects

嘗試

format(str(x), "." + str(n) + "f") 

format(str(x), ".%sf" % n) 
+0

現在它的工作原理!順便說一句你的第二個解決方案非常酷,你能給我一些資源嗎? – mko 2012-08-02 02:56:54

+0

%字符串格式化被折舊...只是一個頭...我仍然使用它很多... – 2012-08-02 02:57:25

+0

@yozloy檢查此http://docs.python.org/library/string.html#format-string-syntax – xiaowl 2012-08-02 03:00:21