Open In App

Find length of a string in python (6 ways)

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Strings in Python are immutable sequences of Unicode code points. Given a string, we need to find its length. Examples:

Input : 'abc'
Output : 3

Input : 'hello world !'
Output : 13

Input : ' h e l   l  o '
Output :14

Methods#1:

  • Using the built-in function len. The built-in function len returns the number of items in a container. 

Python3




# Python code to demonstrate string length
# using len
 
str = "geeks"
print(len(str))


Output:

5

Method#2:

  • Using for loop and in operator. A string can be iterated over, directly in a for loop. Maintaining a count of the number of iterations will result in the length of the string. 

Python3




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


Output:

5

Method#3:

  • Using while loop and Slicing. We slice a string making it shorter by 1 at each iteration will eventually result in an empty string. This is when while loop stops. Maintaining a count of the number of iterations will result in the length of the string. 

Python3




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


Output:

5

Method#4:

  • Using string methods join and count. The join method of strings takes in an iterable and returns a string which is the concatenation of the strings in the iterable. The separator between the elements is the original string on which the method is called. Using join and counting the joined string in the original string will also result in the length of the string. 

Python3




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


Output:

5

Method:5:

  • Using reduce method. Reduce method is used to iterate over the string and return a result of collection element provided to the reduce function. We will iterate over the string character by character and count 1 to result each time. 

Python3




# Python code to demonstrate string length
# using reduce
 
import functools
 
def findLen(string):
    return functools.reduce(lambda x,y: x+1, string, 0)
 
 
# Driver Code
string = 'geeks'
print(findLen(string))


Output:

5

Method:6:

  • Using sum() and list comprehension function. We use list comprehension for iterating over the string and sum function to sum total characters in string 

Python3




# Python code to demonstrate string length
# using sum
 
 
def findLen(string):
    return sum( 1 for i in string);
 
 
# Driver Code
string = 'geeks'
print(findLen(string))


Output:

5

Method 7: Using enumerate function

Python3




# python code to find the length of
# string using enumerate function
string = "gee@1ks"
s = 0
for i, a in enumerate(string):
    s += 1
print(s)


Output

7


Previous Article
Next Article

Similar Reads

Python string length | len() function to find string length
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: C/C++ Code string = "Geeksforgeeks" print(len(string)) Output13String len() Syntax len(string) Parameter String: string of which you want to find the length. Return: It returns
3 min read
Python | Ways to split a string in different ways
The most common problem we have encountered in Python is splitting a string by a delimiter, But in some cases we have to split in different ways to get the answer. In this article, we will get substrings obtained by splitting string in different ways. Examples: Input : Paras_Jain_Moengage_best Output : ['Paras', 'Paras_Jain', 'Paras_Jain_Moengage',
2 min read
Python | Ways to find all permutation of a string
Given a string, write a Python program to find out all possible permutations of a string. Let's discuss a few methods to solve the problem.Method #1: Using Naive Method C/C++ Code # Python code to demonstrate # to find all permutation of # a given string # Initialising string ini_str = "abc" # Printing initial string print("Initial s
2 min read
Python | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.finditer() C/C++ Code import re # Initialising values ini
4 min read
Python - Length of shortest string in string list
Sometimes, while working with a lot of data, we can have a problem in which we need to extract the minimum length string of all the strings in list. This kind of problem can have applications in many domains. Let’s discuss certain ways in which this task can be performed. Method #1 : Using min() + generator expression The combination of the above f
5 min read
Find the Length of a String Without Using len Function in Python
In this program, we are given a string and we have to find out the length of a string without using the len() function in Python. In this article, we will see how we can find the length of a string without using len() function in Python. Example : Input: 'abc' Output : 3 Explanation: Length of 'abc' is 3 Python Program to Calculate the Length of a
3 min read
Python | Ways to remove numeric digits from given string
Given a string (may contain both characters and digits), write a Python program to remove the numeric digits from string. Let's discuss the different ways we can achieve this task. Method #1: Using join and isdigit() C/C++ Code # Python code to demonstrate # how to remove numeric digits from string # using join and isdigit # initialising string ini
6 min read
Python | Ways to convert string to json object
In this article, we will see different ways to convert string to JSON in Python this process is called serialization. JSON module provides functions for encoding (serializing) Python objects into JSON strings and decoding (deserializing) JSON strings into Python objects. Encoding (Serializing) JSON: If you have a Python object and want to convert i
3 min read
Python | Ways to sort letters of string alphabetically
Given a string of letters, write a python program to sort the given string in an alphabetical order. Example: Input : PYTHON Output : HNOPTY Input : Geeks Output : eeGksNaive Method to sort letters of string alphabetically Here we are converting the string into list and then finally sorting the entire list alphabet wise. C/C++ Code s ="GEEKSFO
2 min read
Python | Ways to remove n characters from start of given string
Given a string and a number 'n', the task is to remove a string of length 'n' from the start of the string. Let's a few methods to solve the given task. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # how to remove 'n' characters from starting # of a string # Initialising string ini_string1 = 'garg_akshat' # Initialising nu
3 min read
Article Tags :
Practice Tags :