How do you find the length of the string in Python without importing any libraries?
To find the length of a string in Python use the built-in
len()
function, which takes one parameter that can be of data type string, bytes, tuple, list, range, or a collection (such as a dictionary, set, or frozen set). The len() function, when used on a string, will return the number of characters in that string.
The
len()
built-in function is an abbreviation of the word
length
.
Here’s an example demonstrating the use of this function in the Python REPL:
>>> my_string = "How long is a piece of string?"
>>> len(my_string)
30
As you can see from the above example, I have assigned a string to a variable I’ve labelled
my_string
then, I use the built-in
len()
function and insert the name of the variable into the parameter of the
len()
function to find the total number of characters in that string.
What Does
len()
Count?
It’s important to note that the
len()
function counts the number of characters in the string when it is used on a string data type.
Each element within a string is comprised of
characters
. To know if a character will be recognised in Python use the
ord()
function
by inserting the character into its single parameter. If the
ord()
function returns a number, then the character will be recognised.
If the data type is something other than a string, byte, tuple, list, range or collection then you will get a
TypeError
. For example, if you insert a number or boolean data type you will get a
TypeError
.
Here’s an example of what this would look like in the Python REPL:
>>> len(123456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()
>>> len(True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: object of type 'bool' has no len()
As you can see from the above examples, when an int data type is used in the len() function, it returns a
TypeError
, similarly with the next example where a
bool
data type is used.
How Do You Get The Length Of A Number?
As demonstrated above you cannot use the
len()
function when the data type of the parameter used for
len()
is a number, but there is a simple workaround: convert the number to a string first.
To convert a number to a string, use another built-in function called
str()
, which takes either one parameter or three parameters. I’ll be using the
str()
in this case, which takes only one parameter.
Here’s an example of how to find the length of a number using the
len()
and
str()
built-in functions:
>>> my_int = 123456
>>> len(str(my_int))
6
As you can see from the above example, I can easily convert the
int
data type variable in the
str()
function and wrap that with the
len()
function.
The result is the length of the number.
Alternative To
len()
Function?
Is there an alternative way to count the length of a string without using the
len()
function?
To count the number of characters in a string without using the
len()
function, you could use a list comprehension with the built-in
sum()
function, which would allow you to write an alternative to
len()
that would still be a one-liner.
Here’s an example demonstrating the
sum()
function as an alternative to
len()
:
>>> my_string = "How long is a piece of string?"
>>> sum([1 for x in my_string])
30
As you can see from the above example, the list comprehension produces a list of 1 for each character in the
my_string
variable, and the sum() function totals all the elements in the list, producing the same result as before.
The beauty of this approach is that it allows you to filter out characters that you may not want to count.
Count Length Of String Excluding Space Character
If you want to filter the string to exclude characters, such as the space character, you can either create a new string by modifying the original string and then insert the new string into the
len()
function, or you could use the above
sum()
and list comprehension approach and apply your filter after the for loop.
Here’s an example demonstrating both approaches:
>>> my_string = "How long is a piece of string?"
>>> no_spaces = my_string.replace(' ', '')
>>> print(no_spaces)
Howlongisapieceofstring?
>>> len(no_spaces)
24
Using the first method where the second variable contains the space-less original string by using the built-in
string.replace()
function the approach is fairly straightforward.
Here’s an example demonstrating the
sum()
and list comprehension technique:
>>> my_string = "How long is a piece of string?"
>>> sum([1 for x in my_string if ord(x) != 32])
24
With this type of approach as displayed from the Python REPL output above all that has been added is the filter
if ord(x) != 32
. This condition checks the
ordinal character
in the string and if it represents the same ordinal character as the space character, being 32, then it does not add
1
to the list.
This approach may also be handy if there are other characters you wish to exclude from being in the count such as carriage returns or line feeds.
If you wanted to expand the list of characters to exclude, such that new line or carriage returns were also removed, you would modify the
sum()
list comprehension approach to be something like this:
sum([1 for x in my_string if ord(x) not in [10, 13, 32]])
This would then exclude any new line, return and space characters from being added to the count of characters in your original string.
Summary
To count the number of characters in a string, use the built-in method
len()
which counts each character contained in the string provided the character is recognised by Python.
The
len()
function will return a
TypeError
if the variable inserted into the function is of a data type that does not permit iteration, such as
bool
and numbers.
An alternative approach to using the
len()
function that can permit further filtering on the original string without modifying the original string is to use the
sum()
function with a list comprehension.