We programmers generally use string data in our applications. While using the string data one of the most used operation is getting the size or length of the string. In this tutorial we will look different methods to get the length of the string.
Using Len Function
Python have build in function named len
which will provide the length of the given string. We will just provide the string variable name or string directly to the len
function like below.
myname="poftut.com" len(myname) #10 len("poftut.com") #10

Using SizeOf Function
Another way to get the length of a string is using sys
library provided sizeof
function. sizeof
actually provide the size as byte.
import sys sys.getsizeof(myname) #59 sys.getsizeof("poftut.com") #59

Counting with For
Another and last way is counting the given string by using while
or for
iterations by ourself. As we know strings are just a list of characters so we can iterate over these characters. While iterating we can count the characters. This type of count operation provides some flexibility like skipping some characters and do not add total count. We will use following for loop.
count=0 for ch in myname: count=count+1 print(count) #10

We can create a simple function like below.
def strcount(mystr): count=0 for ch in mystr: count=count+1 return count strcount(myname) 10
