Skip Navigation

Just started learning python - question about types of statements.

Just started as in, I'm about an hour into a 4 hour intro video. Seeing two basic ways of manipulating things and don't understand the difference.

If I want to know the length of a string and I just guess at how to do it I would try one of these two things,

  1. Len(string)
  2. string.len()

What is the difference between these types of statements? How do I think about this to know which one I should expect to work?

20

You're viewing a single thread.

20 comments
  • Are there any other ways I would find the length? Or are methods and functions the only options?

    You could get creative and find several inferior, silly, and utterly insane ways of achieving the same result, for example by treating a string as an interable (read: "list" or "array") of its constituent characters, and count the number of characters. This feels very "example (but not exemplary) code on the first pages of a crappy C++ textbook", but hey, it's a way:

    length = 0
    string = "foobar"
    for char in string:
      length = length + 1
    print(length)
    

    Mind you, this is not programming. This is toying around, and perfectly valid in that way, but no-one in a halfway sane state of mind would dare suggest doing it this way with Python if you actually care about the result. :)

You've viewed 20 comments.