Find length of a string in python (3 ways)


String is a python which is a series of Unicode characters. Once declared it is not changeable. In this article we'll see what are the different ways to find the length of a string.

Using the len()

This is the most straight forward way. Here we use a library function named len(). The string is passed as parameter to the function and we get a count of characters in the screen.

Examples

str ="Tutorials"
print("Length of the String is:", len(str))

Output

Running the above code gives us the following result −

Length of the String is: 9

Using Slicing

We can use the string slicing approach to count the position of each character in the string. The final count of the number of positions in the string becomes the length of the string.

Examples

str = "Tutorials"
position = 0
# Stop when all the positions are counted
while str[position:]:
   position += 1
# Print the total number of positions
print("The total number of characters in the string: ",position)

Output

Running the above code gives us the following result −

The total number of characters in the string: 9

Using join() and count()

The join() and count() string functions can also be used

Examples

str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length)

Output

Running the above code gives us the following result −

The total number of characters in the string: 9

Updated on: 07-Aug-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements