How to get the length of a string in Python?


A string is a group of characters that may be used to represent a single word or an entire phrase. Strings are simple to use in Python since they do not require explicit declaration and may be defined with or without a specifier.

Python has a variety of built in functions and methods for manipulating and accessing strings. Because everything in Python is an object, a string is an object of the String class, which has several methods.

In this article we are going to discuss how to get the length of a string in Python.

Using the len() function

The len() function in python accepts a string as a parameter and returns its length. This function can not only be used for strings but also can be used for lists or any iterable.

Example

In the program given below, we are taking a string as an input, and by using the len() function we are finding out the length of that string.

s1 = "Tutorialspoint" length = len(s1) print("The Length of the string",s1,"is",length)

Output

The output of the above program is,

('The Length of the string', 'Tutorialspoint', 'is', 14)

Using the slice operator

We can also calculate the length of a string using the slice operator. We can use the slice operator to traverse through the string and at each position where a character occurs we will increment the count by a value. The final value of the count will be the length of the string.

Example

In the program given below, we are using taking a string input and we are taking an iterable variable by using the slice operator we are traversing the string and finding the length of the string.

s1 = "Tutorialspoint" i = 0 while s1[i:]: i += 1 print("The length of the string",s1,"is",i)

Output

The output of the above program is,

('The length of the string', 'Tutorialspoint', 'is', 14)

Using the for in loop

We can traverse the string using the loops and count the number of characters in it.

Example

Following is an example −

s1 = "Tutorialspoint" i = 0 for char in s1: i += 1 print("The length of the string",s1,"is",i)

Output

The output of the above program is,

('The length of the string', 'Tutorialspoint', 'is', 14)

Using the join() and count() methods

The join function returns an iterable as the output, so by using the count() method we can find the number of characters in the resultant iterable.

Example

In the example given below, we are using the join() and count() method to find out the number of iterables and count them using count().

s1 = "Tutorialspoint" length=((s1).join(s1)).count(s1) + 1 print("The length of the string",s1,"is",length)

Output

The output of the above program is,

('The length of the string', 'Tutorialspoint', 'is', 14)

Updated on: 19-Oct-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements