Python String Length

python-string-length-ipcisco-1

With Python Strings, to find the length of a string, one of the most used method is len () function. With len () function, we can measure the length of the string. In other words, python len () function returns with python string length.

 

There are also other ways to find the length of a string. These ways are using loop and in operator together or loop and slicing methods together. But these are long methods. So, the better way to find a string’s lenght is using built in python len () function.

 


Would you like to learn also Python List Length?


 

Let’s do an example about python sting length wşth len () function.

 

message = "hello,how are you?"
print(len(message))

 

As you can see above, we have a message and this message has 18 characters including signs and spaces. So, the output of this len () function will be like belw:

 

18

python-string-length-ipcisco-1

 

This is the simple way to find out the lentgh of a python string.

 

 

Let’s do a little complex example and fin the lenth of a string in a different way. Here, we will define our own function.

 

def myfunction(x):
    counter = 0   
    for i in x:
        counter += 1
    return counter
  x = "how are you?"
print(myfunction(x))

 

As you can see above, we have defined a function named myfunction. This function is checking each character of x and increase counter value on efor every time. And when we assign a string to x, our function is checking each character of this x string and return with the lenth of it at the end.

 

12

how-to-calculate-string-length-in-python

During your python coding activities, you will use string lenth method too much. So, instead of creating your own strign lentgh function, using a built in easy funtion, len () is a better way to find python string length.

Back to: Python Programming Course > Python Strings

Leave a Reply

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

Python Programming Course

Collapse
Expand
Latest Blog Posts