Open In App

Find length of a string in python (6 ways)

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:






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

Output:
5

Method#2:






# 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:




# 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:




# 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:




# 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:




# 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




# 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

Article Tags :