×

Python Program to find the length of a string

Python program to find the length of a string

A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters in a string is known as the length of the string. In this article, we'll look at the various methods for determining the length of a string.

Example:  
Input = “ABC” Output = 3  
Input = “Hello” Output = 5

Method 1: Using built-in method len()

The built-in len() method is the simplest way to calculate a string's length in Python. It takes a string as a parameter and returns the length of that string as an integer.

Source Code

The following source code calculates the length of a string with the use of library functions.

#Program to find the length of a string using len()   
#input string str = input("Enter a string: ")   
#prints the result print(len(str))

Output

find the length of a string

Explanation: A built-in function len() returns the number of characters in a string.

Method 2: Using for loop

The following source takes the input string from the user and counts the number of characters in the input string using for loop.

#Program to find length of a string with for loop 
#input string str = input("Enter a string: ") 
#returns length of string def length(str):     
count = 0     for i in str:         temp += 1     return count 
#prints the result print("Length of the input string is:",len(str))

Output

find the length of a string

Explanation: In the above code, we have declared a length() and pass the argument str. We have used the variable temp in for loop to store the number of iterations of string. When the iteration completes, the length of the string will be printed on the screen.

Method 3: Using while loop and slicing

The following source code counts each character's position in the string by using the string slicing method. The string's length is determined by the final count of the number of positions in the string.

#Program to find length of string using slicing approach 
#return string length def length(String1):     count = 0     while String1[count:]:         count += 1     return count 
#Input string String1 = "TUTORIALANDEXAMPLE" 
#prints the result print("Length of the input string is:",len(String1))

Output

find the length of a string

Explanation: Each iteration of slicing a string shorter by one would probably result in an empty string. This is where the while loop comes to an end. The length of the string can be calculated by keeping the count of the number of iterations.


Related Topics

First Unique Character in a String Python

This article aims to introduce you to strings and how to create a string in Python, and then we will solve a simple yet exciting DSA (Data Structures and Algorithms)...

3 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value....

4 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Periodogram in Python

Python:  Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Hypothesis Testing in Python

Hypothesis Testing in python is widely used along with statistics. Many libraries in Python are very useful for statistics and machine learning. Libraries like numpy, scripy etc. help in hypothesis testing in...

12 minutes read.

Find whether the given stringnumber is palindrome or not

Problem statement Sam is found of playing with strings. One day he thought of finding whether a string is a palindrome or not. He wanted to develop a computer process to...

2 minutes read.

Python vs PHP

Python Python is a high-level, object-oriented, interpreted language that is used to create independent program and algorithms for a variety of applications. It has a large library support base. In 1990,...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Rank Based Percentile GUI Calculator using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With the capabilities...

3 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

Amazon rekognition using python

Amazon recognition service is an AI service which is an image labelling API (Application programming interface). In this article, we shall learn to use the AWS python boto3 module to...

3 minutes read.

Ternary operators in python

Starting from Python version 2.5, ternary operators are also known as Conditional operators. Using these operators, we can evaluate any problem based on a condition. It is an alternative and...

4 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

How to Parse JSON in Python

JSON The JSON, the Java Script Object Notation, is an open standard file designed for data interchange; it is light-weighted text. The JSON uses human-readable text to store and transmit the...

4 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.