2 ways to find length of string in Python


There are two main ways to find the length of a string in Python.

The first is to use the built-in len() function. Alternatively, if you do not want to use the len() function, you can use a loop.

In today’s post, we’ll discuss the two approaches above. We’ll also work on a related practice question that requires us to write a Python function for finding string length, while disregarding certain characters.

Using the Python len() Function to Find String Length

Using the Python len() function to find string length is straightforward; you pass the string to the function and it’ll return the number of characters in the string.

Let’s look at some examples:

# Example 1: Passing the string directly to len()

print(len('Hello'))

# Example 2: Passing a variable to len()

msg = 'Hello'
print(len(msg))

# Example 3: String consists of spaces

msg = 'Good Day'
print(len(msg))

# Example 4: String consists of letters, symbols and digits

msg = 'Ab12#'
print(len(msg))

# Example 5: String consists of newline characters

msg = '''
AB
C
'''
print(len(msg))

If you run the code above, you’ll get the following output:

5
5
8
5
6

The first four examples should be self-explanatory.

For the last example, we pass the string

'''
AB
C
'''

to the len() function. This string is enclosed within a set of triple quotes, which are used to create strings that span multiple lines.

When we pass this string to the len() function, the function starts counting immediately after the triple quotes.

The first character it encounters is the newline character '\n' after the opening triple quotes. This character is responsible for pushing AB to the next line. Another two newline characters occur after AB and C.

Therefore there is a total of three newline characters and three letters, as shown in the diagram below, giving us a total of 6.

python string length (with newline)

This is why the len() function returns 6 for the last example.

This example illustrates that whitespace characters (such as a newline character) are included in the count returned by len().

How To Find Length Of String In Python Without Using len()

Next, let’s look at the second approach for finding string length in Python. This approach does not use the built-in len() function. Instead, it uses a loop to find string length.

msg = 'Hello'
length = 0

for i in msg:
    length += 1

print(length)

In the example above, we use a for loop (lines 4 and 5) to iterate over msg. For each iteration, we increment the value of length by 1 (line 5).

If you run the code above, you’ll get 5 as the output.

Similar to the len() function, when we use a for loop to iterate over a string, it counts the number of whitespaces as well. For instance, if you run the code below

msg = '''
AB
C
'''
length = 0

for i in msg:
    length += 1

print(length)

you’ll get 6 as the output. This is because the string (msg) consists of 3 newline characters and 3 letters.

Practice Question

Now that we know how to find the length of a string in Python, let’s apply what we’ve learned on today’s practice question.

Today’s question requires us to write a function called countLettersOnly() that accepts a string as argument. The function counts and returns the number of letters (i.e. A to Z and a to z) in the string.

Hint:

You can use Unicode code points to determine whether a character is a letter. You can refer to this post for a discussion on Unicode code points.

Expected Results

To test your function, you can run the code below:

msg = 'Good Day'
print(countLettersOnly(msg))

msg = '''
AB
C
'''
print(countLettersOnly(msg))

You should get

7
3

as the output.

Suggested Solution

def countLettersOnly(msg):
    length = 0
    for i in msg:
        if (ord(i) >= 65 and ord(i) <= 90) or (ord(i) >= 97 and ord(i) <= 122):
            length += 1

    return length

The function above uses a for loop that is very similar to the loop we used in the section “How To Find Length Of String In Python Without Using len()“.

The only difference is we added an if condition on line 4 to determine if i is a letter. We do that using the Python ord() function. This function gives us the Unicode code point of a character.

If the code point is between 65 and 90, it is an uppercase letter (A to Z). If it is between 97 and 122, it is a lowercase letter (a to z).

We determine the code point of i on line 4 and increment the value of length if the code point indicates that i is an uppercase or lowercase letter.

After iterating over all the characters in msg, we return the value of length.

Written by Jamie | Last Updated December 9, 2020

Recent Posts