5 Best Ways to Find Python String Length

What is Python String Length?

Python string length is the function through which we find the length of the string. There is an inbuilt function called len() in python, so this len() function finds the length of the given string, array, list, tuple, dictionary, etc.

Through the len() function, we can optimize the performance of the program. The number of elements stored in the object is never calculated, so len() helps provide the number of elements.

Syntax

len(string)

Parameters

String : This will calculate the length of the value passed in the string variable.

Return Value

It will return an interger value i.e. the length of the given string.

Various Type Of Return Value

  1. String
  2. Empty
  3. Collection
  4. Type Error
  5. Dictionary

1. String:

It is used to return the number of characters present in the string, including punctuation, space, and all types of special characters. However, it would help if you were careful while using the len of a Null variable.

2. Empty:

In this the return call has the zero characters, but it is always None.

3. Collections:

The len() built in function return the number of elements in the collection.

4. Type Error:

Len function always depends on the type of the variable passed to it. A Non-Type len() does not have any built-in support.

5. Dictionary:

In this, each pair is counted as one unit. However, Keys and values are not independent in the dictionary.

Ways to find the length of string in Python

Ways to find the length of string

1. Using the built-in function len()

# Python code to demonstrate string length  
# using len 

str = 'Latracal'
print(len(str))

output:

8

Explanation:

In this code, we have taken str as the variable in which we have stored the string named ‘Latracal’ and then applied the len() in which we have put str in between. so the output came is 8 as the word ‘Latracal‘ contains 8 characters.

2. Using for loop to Find the length of the string in python

 A string can be iterated over easily and directly in for loop. By maintaining a count of the number of iterations will result in the length of the string.

# Python code to demonstrate string length  
# using for loop 
  
# Returns length of string 
def findLength(str): 
    counter = 0    
    for i in str: 
        counter += 1
    return counter 
  
  
str = "Latracal"
print(findLength(str))

output:

8

Explanation:

In this code, we have used for loop to find the length of the string. Firstly, we have taken an str variable that we have given ‘Latracal’ as the string. Secondly, we have called the findLength function in which we have counter equals 0, After that, for loop was written from 0 to string, and the counter value gets increased by 1 at a time. At last, we have printed the counter value.

3. Using while loop and Slicing

We slice a string making it shorter by 1 at regular intervals to time with each iteration till the string is the empty string. This is when the while loop stops. By maintaining a count of the number of iterations will result in the length of the string.

# Python code to demonstrate string length  
# using while loop. 
  
# Returns length of string 
def findLength(str): 
    count = 0
    while str[count:]: 
        count = count + 1
    return count 
  
str = "LatracalSolutions"
print(findLength(str)) 

output:

17

Explanation:

In this code, we have used for loop to find the length of the string. Firstly, we have taken an str variable in which we have given ‘LatracalSolutions’ as the string. Secondly, we have called the findLength function in which we have set the value of count equals 0. Thirdly, then applied the while loop in which we are slicing the value of str by one at each iteration till the string becomes empty. And at last, returned the count value.

4. Using string methods join and count

The join method of strings takes in an iteration and returns a string which is the concatenation of the iteration strings. The separator present in the between of elements is the original string on which the method is called. Using the join and count method, the joined string in the original string will also result in the string’s length.

# Python code to demonstrate string length  
# using join and count 
  
# Returns length of string 
def findLength(str): 
    if not str: 
        return 0
    else: 
        some_random_str = 'py'
        return ((some_random_str).join(str)).count(some_random_str) + 1
  
str = "LatracalSolutions"
print(findLength(str))

output:

17

Explanation:

In this code, we have used for loop to find the length of the string. Firstly, we have taken an str variable in which we have given ‘LatracalSolutions’ as the string. Secondly, then we have called the findLength function in which we have applied if and else function in which if contains the conditions that if the string is empty, it should return 0; otherwise, the else part will work. We have taken some random string ‘py’ in which the main string will get join by the iteration, and the count value will increase till the string becomes empty. After that, the output gets printed.

5. Using getsizeof() method to Find Length Of String In Python

This method is used to find the object’s storage size that occupies some space in the memory.

Note: This method is only applicable for normal ascii letters. If you have a special character it’ll not work, as it uses the size of the string in bytes. So be careful while using it!

import sys
s = "pythonpool"
print(sys.getsizeof(s) - sys.getsizeof(""))

Output:

10

Explanation:

Here, we have used the sys module which is inbuilt in python. then we have to take a string s and using the sys module with the getsizeof() method printed the length of the string.

Example to Find Length of String in Python

# Python code to demonstrate string length
# testing len() 
str1 = "Welcome to Latracal Solutions Python Tutorials"
print("The length of the string  is :", len(str1))

Output:

The length of the string  is : 46

Must Read

Summary: Python String Length

We’ve seen all 5 different ways of finding the string length, but in conclusion, only one of them is practical. In-built len() keyword is the best way to find the length of the string in any type of format.

  • Python len() is a built-in function. You can use the len() to find the length of the given string, array, list, tuple, dictionary, etc.
  • String: This will calculate the length of the value passed in the string variable.
  • Return value: It will return an integer value i.e. the length of the given string.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Nobody
Nobody
3 years ago

There is one best way to get the length of a string, which is using len(). And then there are 4 other more or less bad ways to get the length. And the getsizeof() can even produce completely wrong results, because it returns the size of the object.

For example:

>>> import sys
>>> sys.getsizeof('föö') - sys.getsizeof('')
27
>>> 
>>> help(sys.getsizeof)
Help on built-in function getsizeof in module sys:


getsizeof(...)
    getsizeof(object [, default]) -> int
    
    Return the size of object in bytes.
Python Pool
Admin
3 years ago
Reply to  Nobody

Hi, thank you for your explanation.

Yes, getsizeof() is a non-practical way to find the length of string but to make aware of such hidden functions we’ve mentioned it.
I’ve updated the getsizeof() section with a special note.

Pratik Kinage
Admin
3 years ago
Reply to  Nobody

So our x variable manages which player will play a specific turn. So, if x is even i.e x%2 == 0 then player1 will play the game. Otherwise, player2 will play the game.
Then, we’ll change the text of the button by calling the specific button widget. In this case, b1.config(text=y) is used. Moreover, the boards[number] stores the value of each player’s turns.