2012-08-02 2 views
0

Je dois faire un quiz python.Comment résoudre cette interpolation de chaîne Python liée?

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

Ce que je ne faisais que:

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

Je suis l'erreur:

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

Là où je fait de mal?

+0

Comme cela ressemble à des devoirs que je ne vais pas donner une réponse, mais vérifier transtypage dans [Python] (http: // docs.python.org/library/functions.html#str). – adchilds

+0

regardez la mise en forme de chaîne son typiquement '" ". Format (arg1, arg2, ...)' –

Répondre

3

cannot concatenate 'str' and 'int' objects

Essayez

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

ou

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

Maintenant ça marche! BTW votre 2ème solution est assez cool, pourriez-vous me donner quelques ressources à ce sujet? – mko

+0

% mise en forme de chaîne est dépréciée ... juste un heads-up ... Je l'utilise encore beaucoup ... –

+0

@yozloy vérifier cela http://docs.python.org/library/string.html#format-string-syntax – xiaowl