我需要做一個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
我哪裏做錯了?
由於這看起來像功課,我不會給出答案,但檢查出型鑄造在[Python中(HTTP:// docs.python.org/library/functions.html#str)。 – adchilds 2012-08-02 02:44:08
查看字符串格式化它的典型'「」。格式(arg1,arg2,...)' –
2012-08-02 02:54:25