2
>>> '{lst.__len__()}'.format(lst=[1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__len__()'

Plz help me out and thank you for your help in advance.....

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
  • Please avoid linking to third party sites where at all possible. Please post code rather than images. That said, the errors are helpful, and are your answer. – John Jun 03 '18 at 08:55
  • 1
    Look at [this answer](https://stackoverflow.com/a/45736151/342544), it might help. – Henno Brandsma Jun 03 '18 at 09:02
  • What you want to get? Length of the the `lst` as string, or something else? – Mark Mishyn Jun 03 '18 at 09:03
  • You get the length of a list by using `len([1,2,3,4])` . Avoid directly calling any method that look like `__XXXXXX__()` - by convention they should not be called from the outside. There are methods that will call them, like `len()` , `str()`, `next()` etc. Your code could be changed to `'{}'.format(len([1,2]))` to get the lenght of the list as string. – Patrick Artner Jun 03 '18 at 09:10
  • Thanks a lot everyone.Really happy to see your responses and they helped.I got to understand this behaviour of string formatting from this useful link https://stackoverflow.com/questions/45736050/formatting-dict-keys-attributeerror-dict-object-has-no-attribute-keys – Simranjeet Singh Jun 03 '18 at 10:06

1 Answers1

0

You can't call methods in string placeholders, You can only access attributes or also index the values.

For what you wanna do, you can do the following but it's not secure and you should use it with caution.

eval('{lst}'.format(lst=[1,2])).__len__()

Otherwise, well no, placeholders can't be used to invoke methods.

SpiXel
  • 4,338
  • 1
  • 29
  • 45
  • bad advice. `'{}'.format(len([1,2]))` is safe and will return the string representation of the list-length which the OP would as well (if working as intended) and yours does not - it returns the int. – Patrick Artner Jun 03 '18 at 09:15
  • Well, I reckon it works but it's not exactly what the OP had in mind, he originally wanted to pass the list dynamically, you're kinda not doing that. Yes there's the way you suggested and probably a handful of other ways :) – SpiXel Jun 03 '18 at 09:17