Python String Length: How to Find the Length of String

Python string is a data type used to represent a sequence of characters.

Strings are implemented using the str type, and they can be created using single or double quotes

Strings are an immutable sequence of Unicode code points.

Python string length

There is a built-in function called len() to find the length of the string in Python. The len() method takes an argument where you may provide a string and returns the length of the given string.

# app.py

ST = "Millie Bobby Brown"
print("The String length of Millie Bobby Brown is:",len(ST))

BB = "Brayan Cranston"
print("The String length of Brayan Cranston is:", len(BB))

See the output.

➜  pyt python3 app.py
The String length of Millie Bobby Brown is: 18
The String length of Brayan Cranston is: 15
➜  pyt

Alternative approaches

Another technique is to use a for loop with in operator to find a string length.

We will use Python for loop and in operator to find the length of a string.

# app.py

def length(str):
    counter = 0
    for i in str:
        counter += 1
    return counter


str = "Millie Bobby Brown"
print(length(str))

See the output.

➜  pyt python3 app.py
18
➜  pyt

Using a while loop and slicing

We can slice a string making it shorter by one at each iteration will eventually result in an empty string. This is when the while loop stops.

Maintaining the count of the number of iterations will result in the length of the string.

# app.py

def length(str):
    counter = 0
    while str[counter:]:
        counter += 1
    return counter


str = "Millie Bobby Brown"
print(length(str))

See the output.

➜  pyt python3 app.py
18
➜  pyt

Using join() and count() methods

Python join() method takes in an iterable and returns the string, which is the concatenation of the strings in the iterable.

The separator between the items is the original string on which the method is called.

Using the join and counting the joined string in the original string will also result in the length of the string.

def length(str):
    if not str:
        return 0
    else:
        some_random_str = 'Leonard Nimoy'
        return ((some_random_str).join(str)).count(some_random_str) + 1


str = "Millie Bobby Brown"
print(length(str))

See the output.

➜  pyt python3 app.py
18
➜  pyt

How to get the size of a string in bytes in Python

To get the string size in bytes, you need the sys.getsizeof() method.

# app.py

import sys

str = "Millie Bobby Brown"
print("The byte size of Str is: ", sys.getsizeof(str))

See the output.

➜  pyt python3 app.py
The byte size of Str is:  67
➜  pyt

Getting the user to enter string length

The following small program of Python takes user input using the input function. Then, the length of the entered string is displayed using the len() function.

# app.py

data = input('Enter a string? ')

print ("The length of entered string = ", len(data))

See the output.

➜  pyt python3 app.py
Enter a string? KRUNAL
The length of entered string =  6
➜  pyt

This may be useful where your program requires user input, and there is some limitation for entering the number of characters.

# app.py

data = ['Millie', 'Finn', 'Noah', 'Gaten', 'Caleb', 'Sadie']

print ("The length of entered list = ", len(data))

See the output.

➜  pyt python3 app.py
The length of entered list =  6
➜  pyt

Tips and best practices for working with string length in Python

  1. To get a length of a string, use the len() function. For example, if you have a string s = “AppDividend”, you can find the length using the len(s) function.
  2. To find the longest string in the list, use the max() function and pass that in the list as the first argument and key=len as the second argument.
  3. To pad a string with spaces or other characters to a specific length, use the rjust(), ljust(), and center() methods.

Conclusion

The simple and easiest way to find a length of a string is to use the len() method in Python.

Other approaches we have seen can be used for a specific purpose and do not have to be used in every scenario.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.