Lessons · Python · how long is this text
How long is this text
len(s) counts the characters in a string, spaces and punctuation included.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Passwords that must be eight characters, posts that must fit, a column that must not overflow: length checks are everywhere, and len is the whole check.
How to think about it
Count characters, not words: every letter, digit, space and symbol is one. If you want words, split first and count the pieces.
Worked example
word = "python"Six characters.
print(len(word))6.
print(len("a b"))3: the space counts.print(len(""))0: the empty string has no characters.print(len("hi there".split()))2: words, because split made a list of two.Your turn
Refuse a name shorter than three characters.
too_short = (name) < 3
Solve one with the tests running
The trap
len counts characters, not bytes: 'é' is one character but may be two bytes. Length is about what a person sees.
Practise how long is this text on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.