Web development and Tech news Blog site. WEBISFREE.com

HOME > python

Finding Length of String in Python, len()

Last Modified : 04 Oct, 2023 / Created : 04 Oct, 2023
111
View Count


We will learn how to find the length of a string in Python.



# Finding Length of Python String


The built-in function len() can be used to find the length of a string.

len(string)

len() takes a string as an argument and returns its length as a number.

If the type is not a string, you need to convert it into a string first and then find its length as shown below.
len(str(textString))

In this case, the str() function is used to convert it into a string. If it’s not a string, an error like the one below may occur. For example, if it's an int type...
object of type 'int' has no len()

Now, let's create a simple example to understand this in detail.


! Viewing Python len() Function Examples

Below are simple examples where the length of a few strings is printed using the len() function.
len('123')

// Result
3


len('webisfree')
// Result
9


len()
// Error occurred it needs at least one argument

As seen above, it was easy to obtain the length of the string.

Note that len() can also be used to get the length of list type (arrays) similarly to string types.
len(['a', 'b', 'c'])

// Result
3


So far, we have briefly learned about the function len() that helps to find the length of a string.
Perhaps you're looking for the following text as well?

    Previous

    Check for the existence of a Python file, isfile

    Previous

    Using if statement in python and examples