To calculate and print the length of a provided string of characters / words using Python 3.
There are many simple ways to find the length of a string in Python. We will discuss some of those techniques in this short tutorial, alongside with the required Python 3 code.
Using len() function:
The len() function calculates and returns the length of a given string. It considers white spaces in the calculation.
mystring = 'Calculate the length of this string' print("String:", mystring) print("String length:",len(mystring))
String: Calculate the length of this string String length: 31
Using For loop:
Initially, we assign an integer with a value of 0. Then by using For loop, we will loop through each element in the string. For each iteration, the count value is increased by 1. Hence, by the end of the loop, we would have the length of the string.
def getlength(value): count=0 for i in value: count+=1 return count mystring = "My name is John" print("String:", mystring) print("String length:",len(mystring))
String: My name is John String length: 15
Using join() and count() function:
In this technique, we would initialize a sample string. Using the join() function, we would concatenate each character of the provided string value with the sample string. Using count(sample_string)+1, we would count the concatenated sample string with the addition of 1. Thus we obtain the length of the provided string.
def getlength(value): sample_string = 'ab' return sample_string.join(value).count(sample_string)+1 mystring = 'Calculate my length' print("String:", mystring) print("String length:",getlength(mystring))
String: Calculate my length String length: 19
- sample_string.join(value) – Will provide with output like the screenshot below.