Get the length of a String in Python

avatar

Borislav Hadzhiev

Tue Jun 14 20222 min read

banner

Photo by Tony Pham

Get the length of a String in Python #

Use the len() function to get the length of a string, e.g. result = len(my_str). The len() function returns the length (the number of items) of an object and can be passed a sequence (a string, list, tuple, range or bytes) or a collection (a dictionary, set, or frozen set).

main.py
# ✅ get the length of a string my_str = 'abcd' result_1 = len(my_str) print(result_1) # 👉️ 4 # ✅ get the length of a string in a list my_list = ['ab', 'cde'] result_2 = len(my_list[0]) print(result_2) # 👉️ 2

The len() function returns the length (the number of items) of an object.

The first example shows how to get the length of a string.

If you have a list of strings, make sure to access the list at a specific index to get the length of a string.

Indices are zero-based, so the index of the first character in the string is 0, and the index of the last is len(my_str) - 1.

The last character in the string can also be accessed using -1.

main.py
my_str = 'abcd' print(len(my_str)) # 👉️ 4 print(my_str[0]) # 👉️ 'a' print(my_str[-1]) # 👉️ 'd' print(my_str[len(my_str) - 1]) # 👉️ 'd'

If you need to count the number of occurrences of a substring in a string, use the str.count() method.

main.py
my_str = 'apple' result = my_str.count('p') print(result) # 👉️ 2

The example shows that the letter p can be found 2 times in the string apple.

You can also use the len() function to check if a string is empty.

main.py
my_str = '' if len(my_str) == 0: # 👇️ this runs print('string is empty') else: print('string is NOT empty')

If a string has a length of 0, then it's empty.

You might also see examples online that check whether the string is truthy (to check if it contains at least 1 character), which is more implicit.

main.py
my_str = '' if my_str: print('string is NOT empty') else: # 👇️ this runs print('string is empty')

All values that are not truthy are considered falsy. The falsy values in Python are:

  • constants defined to be falsy: None and False.
  • 0 (zero) of any numeric type
  • empty sequences and collections: "" (empty string), () (empty tuple), [] (empty list), {} (empty dictionary), set() (empty set), range(0) (empty range).

Notice that an empty string is a falsy value, so if the string is empty, the else block is ran.

If you need to check if the string is empty using this approach, you would negate the condition with not.

main.py
my_str = '' if not my_str: # 👇️ this runs print('string is empty') else: print('string is NOT empty')
Use the search field on my Home Page to filter through my more than 1,000 articles.