Skip to content

Python string length | len() function and Other ways

  • by

The best way to get Python string length is by using the len() function. len() function is an inbuilt function in the Python programming language.

You can use other ways also to find the length of Given a string. Here are the ways to find the length of a string in python without using the len() function in Python.

Syntax

len(str)

Return Value

It’s returns the length(in number) of the string.

String len() python example

The following example shows the usage of len() method to get the string size.

str = "Hello Python"
print(len(str))

Output: 12

Python string length 0

If String is of length zero that means it is an empty string. If you try to print this string, then it will print nothing.

str1 = ""
print(str1)
if len(str1) == 0:
    print('empty String')



Output: You can see the empty space of string in console.

Python string length len function

Q: How to find the size of the string in bytes in Python?

Answer: If you want the number of bytes in a string, this code should do work for you.

The output will be number because encapsulated in a string is a bunch of other information due to the fact that strings are actual objects in python.

str1 = "Hello"
print(len(str1.encode('utf-8')))

Output: 5

Q: How to find the length of the string in python without using the len method?

Answer: You can use loop and in operator and other method to get size of string.

A string will be iterated over, directly in a for-loop and count the number of iterations. It will be the result of the length of the string.

# Returns length of string 
def findLen(str):
    counter = 0
    for i in str:
        counter += 1
    return counter

str1 = "EyeHunts"
print(findLen(str1))

Output: 8

Do comment if you have any doubts and questions on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Python sets Examples are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *