The Wayback Machine - https://web.archive.org/web/20240927193054/https://www.geeksforgeeks.org/python-string-length-len/
Open In App

Python string length | len() function to find string length

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method.

Example:

Python
string = "Geeksforgeeks"
print(len(string))

Output
13

String len() Syntax

len(string) 

Parameter

String: string of which you want to find the length.

Return:

It returns an integer which is the length of the string. 

What is the String len() Function?

The string len() function is a built-in function in Python that is used to find the length of the string. You can know the number of characters in a string using this function.

It is a very important string function, and it is very easy to use.

How to Use String len() Function?

You can easily use the String len() function, just pass the string as the parameter in the function. Let’s look at an example to understand how to find the length of the string in Python.

More Examples of String len() Function

The len() method is used to find the length of an object in Python. By using len(), we can find the length of strings and lists. In this example, we are finding the length of a string.

Example 1: Len() function with tuples and string

In this example, we are counting the length of the tuples and list.

Python
# Python program to demonstrate the use of
# len() method  

# with tuple
tup = (1,2,3)
print(len(tup))

# with list
l = [1,2,3,4]
print(len(l))

Output
3
4

Example 2: Python len() TypeError

In this example, we are using len() with a boolean value and find TypeError as a result.

Python
print(len(True))

Output

TypeError: object of type 'bool' has no len()

Example 3: Python len() with dictionaries and sets

In this example, we are using Python len() with dictionaries and sets to find the length of dictionary and set.

Python
# Python program to demonstrate the use of
# len() method  

dic = {'a':1, 'b': 2}
print(len(dic))

s = { 1, 2, 3, 4}
print(len(s))

Output
2
4

Example 4: Python len() with custom objects

In this example, we are using len() to find the length of custom objects and to find the length of an object in Python.

Python
class Public:
    def __init__(self, number):
        self.number = number
    def __len__(self):
        return self.number
    
obj = Public(12)
print(len(obj))

Output
12

Example 5: Python len() with range()

In this example, we are using the len() function to find the length of the range() function.

Python
l=range(1,10)
print(len(l))

Output
9

In this article, we have covered about Python string len() function and discussed its working. len() function is used to find the length of a string. It is a very common yet important function of string methods.

Read More String Methods

Also Read:

Python string length | len() function to find string length – FAQs

What is the len() Function in Python?

The len() function in Python is a built-in function that returns the number of items in an object. When the object is a string, the len() function returns the number of characters in the string. It can also be used with other iterable types, such as lists, tuples, dictionaries, and sets, to determine the number of elements contained within them.

Which Length Function is Used to Find the Length of the String?

In Python, the len() function is used to find the length of a string. It counts all characters in the string, including letters, digits, punctuation, and whitespace characters, and returns the total count.

Example:

my_string = "Hello world"
length = len(my_string)
print(length) # Output: 11

What is String Size and String Length?

  • String Size: Typically refers to the amount of space (in bytes) a string occupies in memory. This is more relevant in languages where you need to manage memory explicitly or where the string encoding affects its size in memory.
  • String Length: Refers to the number of characters in the string. This is what functions like len() in Python measure. The length of the string is the total count of its characters.

In Python, the distinction between size and length might come into play with different encodings or with data types that include binary data, but for ordinary strings, len() gives you the count of characters, which is usually what’s meant by length.

Does len() Start from 0?

The len() function does not start counting from 0. It returns the total number of elements in the object. For example, if a string has 10 characters, len() returns 10. The index of elements in Python starts from 0, but the len() function returns the count of total elements.

Does String len() Count Spaces?

Yes, the len() function counts spaces as characters when calculating the length of a string. Every character, including spaces, punctuation, special characters, and normal alphabetic or numeric characters, is counted as one towards the total length.

Example:

my_string = "Hello world"  # Includes a space between 'Hello' and 'world'
print(len(my_string)) # Output: 11, including the space

These uses and behaviors of the len() function make it a versatile tool for working with data structures in Python, providing a simple way to obtain their sizes.



Previous Article
Next Article

Similar Reads

Internal Working of the len() Function in Python
The len() function in Python has a very peculiar characteristic that one had often wondered about. It takes absolutely no time, and equal time, in calculating the lengths of iterable data structures(string, array, tuple, etc.), irrespective of the size or type of data. This obviously implies O(1) time complexity. But have you wondered How? Python f
2 min read
Python len() Function
Python len() function is an inbuilt function in Python. It can be used to find the length of an object. Python len() function Syntax: len(Object) Parameter: Object: Object of which we have to find the length for example string, list, etc. Returns: It returns the integer value which indicates the length of an object. For example, we can find the tot
2 min read
Python String Methods | Set 2 (len, count, center, ljust, rjust, isalpha, isalnum, isspace & join)
Some of the string methods are covered in the set 3 below String Methods Part- 1 More methods are discussed in this article 1. len() :- This function returns the length of the string. 2. count("string", beg, end) :- This function counts the occurrence of mentioned substring in whole string. This function takes 3 arguments, substring, beginning posi
4 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
Python | Pandas Series.str.len()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas str.len() method is used to determine length of each string in a Pandas series. This method is only for series of strings. Since
3 min read
Write your own len() in Python
The method len() returns the number of elements in the list or length of the string depending upon the argument you are passing. How to implement without using len(): Approach: Take input and pass the string/list into a function which return its length.Initialize a count variable to 0, this count variable count character in the string.Run a loop ti
2 min read
Maximum length of consecutive 1's in a binary string in Python using Map function
We are given a binary string containing 1's and 0's. Find the maximum length of consecutive 1's in it. Examples: Input : str = '11000111101010111' Output : 4 We have an existing solution for this problem please refer to Maximum consecutive one’s (or zeros) in a binary array link. We can solve this problem within single line of code in Python. The a
1 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
Find the length of each string element in the Numpy array
NumPy builds on (and is a successor to) the successful Numeric array object. Its goal is to create the corner-stone for a useful environment for scientific computing. NumPy provides two fundamental objects: an N-dimensional array object (ndarray) and a universal function object (ufunc). In this post we are going to discuss ways in which we can find
3 min read
Python | Find whether all tuple have same length
Given a list of tuples, the task is to find whether all tuple have same length. Below are some ways to achieve the above task. Method #1: Using Iteration C/C++ Code # Python code to find whether all # tuple have equal length # Input List initialization Input = [(11, 22, 33), (44, 55, 66)] # printing print("Initial list of tuple", Input) #
6 min read
How to Fix: Length of values does not match length of index
In this article we will fix the error: The length of values does not match the length of the index in Python. Cases of this error occurrence: C/C++ Code # importing pandas import pandas as pd sepal_length = [5.1, 4.9, 4.7, 4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9] sepal_width = [4.6, 5.0, 5.4, 4.6, 5.0, 4.4, 4.9, 5.1, 5.2, 5.3] petal_length = [3.3, 4.6, 4
2 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
numpy string operations | find() function
numpy.core.defchararray.find(arr, sub, start=0, end=None) is another function for doing string operations in numpy.It returns the lowest index in the string where substring sub is found for each element in arr within the range start to end.It returns -1 otherwise. Parameters: arr : array_like of str or unicode. sub : [str or unicode] The substring
2 min read
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solv
1 min read
Python map function to find row with maximum number of 1's
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s. Examples: Input: matrix = [[0, 1, 1, 1], [0, 0, 1, 1], [1, 1, 1, 1], [0, 0, 0, 0]] Output: 2 We have existing solution for this problem please refer Find the row with maximum number of 1's. We can solve this problem in python quickly using map() function
1 min read
How to find the number of arguments in a Python function?
In this article, we are going to see how to count the number of arguments of a function in Python. We will use the special syntax called *args that is used in the function definition of python. Syntax *args allow us to pass a variable number of arguments to a function. We will use len() function or method in *args in order to count the number of ar
3 min read
How to use Glob() function to find files recursively in Python?
Glob is a general term used to define techniques to match specified patterns according to rules related to Unix shell. Linux and Unix systems and shells also support glob and also provide function glob() in system libraries. In Python, the glob module is used to retrieve files/pathnames matching a specified pattern. The pattern rules of glob follow
4 min read
How to find length of dictionary values?
In Python, Dictionary is a collection of unordered data values. Dictionaries are also changeable and indexed. Dictionary holds key:value pair and they are written inside curly brackets. Each key:value pair maps the key to its associated value. Here we use isinstance() method to check the type of the value whether it is a list, int, str, tuple, etc.
6 min read
Find length of one array element in bytes and total bytes consumed by the elements in Numpy
In NumPy we can find the length of one array element in a byte with the help of itemsize . It will return the length of the array in integer. And in the numpy for calculating total bytes consumed by the elements with the help of nbytes. Syntax: array.itemsize Return :It will return length(int) of the array in bytes. Syntax: array.nbytes Return :It
1 min read
Find the length of the text of the first given tag using BeautifulSoup
In this article, we are going to Find the length of the text of the first given tag using BeautifulSoup. Let us see a sample example. Using 'html.parser' it is parsed and the tag value 'h2' length is calculated in the below code soup = BeautifulSoup(html_doc, 'html.parser') specifies that entire given HTML document is parsed using html.parser. The
4 min read
Python | Permutation of a given string using inbuilt function
A permutation, also called an “arrangement number” or “order”, is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation. Examples: Input : str = 'ABC' Output : ABC ACB BAC BCA CAB CBA We have existing solution for this problem please refer Permutations of a given
2 min read
Python String - removeprefix() function
Python String removeprefix() function removes the prefix and returns the rest of the string. If the prefix string is not found, then it returns the original string. It is introduced in Python 3.9.0 version. Python String removeprefix() Method Syntax Syntax: str_obj_name.removeprefix(prefix Parameters: prefix- prefix string that we are checking for.
2 min read
Call a function by a String name - Python
In this article, we will see how to call a function of a module by using its name (a string) in Python. Basically, we use a function of any module as a string, let's say, we want to use randint() function of a random module, which takes 2 parameters [Start, End] and generates a random value between start(inclusive) and end(inclusive). Here, we will
3 min read
Python String upper() Function
Python String upper() method converts all lowercase characters in a string into uppercase characters and returns it. Example: C/C++ Code original_text = "lisT Upper" upper_text = original_text.upper() print(upper_text) OutputLIST UPPER What is the String upper() Method?String upper() is an in-built function in Python, that converts all th
4 min read
Python String Methods | Set 1 (find, rfind, startwith, endwith, islower, isupper, lower, upper, swapcase & title)
Some of the string basics have been covered in the below articles Strings Part-1 Strings Part-2 The important string methods will be discussed in this article1. find("string", beg, end) :- This function is used to find the position of the substring within a string.It takes 3 arguments, substring , starting index( by default 0) and ending index( by
4 min read
Find all the patterns of “1(0+)1” in a given string using Python Regex
A string contains patterns of the form 1(0+)1 where (0+) represents any non-empty consecutive sequence of 0’s. Count all such patterns. The patterns are allowed to overlap. Note : It contains digits and lowercase characters only. The string is not necessarily a binary. 100201 is not a valid pattern. Examples: Input : 1101001 Output : 2 Input : 1000
2 min read
Find the first repeated word in a string in Python using Dictionary
Prerequisite : Dictionary data structure Given a string, Find the 1st repeated word in a string. Examples: Input : "Ravi had been saying that he had been there" Output : had Input : "Ravi had been saying that" Output : No Repetition Input : "he had had he" Output : he We have existing solution for this problem please refer Find the first repeated w
4 min read
Python Dictionary to find mirror characters in a string
Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on. Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end. Input : N = 6 pneumonia Output : pneumlmrz We hav
2 min read
Article Tags :
Practice Tags :