Python len() function
len()
Function in Python
The len()
function in Python is used to determine the length (i.e., the number of characters) of a string. It can also be used with other data types like lists, tuples, dictionaries, and more, but when applied to strings, it counts the total number of characters in the string.
Syntax:
string
: The string whose length you want to find.
Example:
In the example above:
- The string
"Hello, Python!"
has 13 characters, including spaces and punctuation. - The
len()
function returns13
because it counts every character.
Example with an empty string:
Here, the string is empty, so len()
returns 0
.
Example with spaces:
In this example, there are three spaces in the string, and len()
counts each space, returning 3
.
Key Points:
- Whitespace characters like spaces, tabs, and newlines are also counted by the
len()
function. - The function works with any iterable (not just strings), such as lists, tuples, and dictionaries.