Error de Python str no invocable

I know I'm missing something simple here:

>>> mystring = "abcdefghijk"
>>> if mystring(len) > 9:
...     mySlice = mystring[:8]

I just want to slice "mystring" to 8 characters, why I'm getting this error:

Runtime error : 'str' object is not callable

¡Gracias!

preguntado el 09 de marzo de 12 a las 14:03

Learn to look at the full traceback: File "<stdin>", line 1, in <module> TypeError: 'str' object is not callable. Tu if clause is two lines long. The traceback says the error is in line 1, where, as others have pointed out, you have tried to call the string. -

6 Respuestas

You have an error in your syntax (you're trying to call "mystring"). This should work:

>>> mystring = "abcdefghijk"
>>> if len( mystring ) > 9:
...     mySlice = mystring[:8]

respondido 09 mar '12, 14:03

Cambiar mystring(len) a len(mystring)

respondido 09 mar '12, 14:03

Tienes que usar len(mystring) en lugar de mystring(len).

You're either confusing it with a object-method-type call such as mystring.len() (which also won't work), have committed a slight typo, or are dyslexic :-)

I'm guessing it's the middle of those three.

respondido 09 mar '12, 15:03

It goes len(string), and to call a function it would be string.func() anyway.

respondido 09 mar '12, 14:03

Others pointed the error, but you can truncate it right away. No need to check for the length (if you don't want to add some ellipsis there or something):

foo = 'textual data'
print foo[:100]

respondido 09 mar '12, 15:03

The error info contains the corresponding line number.

Respondido 19 Jul 12, 22:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.