0

I'm required to do a python quiz.

here is question:

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).

What I did was:

>>> 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) 

I got the error:

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

Where I did wrong?

2
  • As this looks like homework I won't give an answer, but check out type-casting in Python. Commented Aug 2, 2012 at 2:44
  • look at string formatting its typically "<SomeFormatString>".format(arg1,arg2,...) Commented Aug 2, 2012 at 2:54

1 Answer 1

3

cannot concatenate 'str' and 'int' objects

Try

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

or

format(str(x), ".%sf" % n) 
Sign up to request clarification or add additional context in comments.

2 Comments

Now It works! BTW your 2nd solution is pretty cool, could you give me some resource about it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.