len() is one of the most useful functions. We probably use it more often
on lists than strings, but it gets used for strings very frequently too.
Suppose you want to take a string and underline it:
s = 'Hello world'
print(s + '\n' + '-'*len(s))
The string ‘\n’ is not a literal backslash followed by ‘n’, it is an
escape-code for a newline character. So the above code computes:
how many characters are in s?
make a row of dashes that many characters long
concatenate a newline and the row of dashes after s
and print it
Which will give us:
x Hello world
(Please ignore the ‘x’ column, that is there to prevent the Discourse
software from deleting everything after the line of dashes.)
password = input("Please enter your new password: ")
if len(password) < 10:
print("Password is too short, please try another one.")
A lot of the time, the call to len() will be hidden inside other string
methods. For example, if you call one of the methods:
to align the string to a certain width, internally the method needs to
know how long the string is so it knows how much padding to use:
'Hello world'.center(20, '-')
# returns '----Hello world-----'