29-Jun-2021
.
Admin
Hi Guys,
In this blog, I will show you how to get length of string in python. We will learn how to find length of string using python. I would like to share python get length of string example.
This article will give example of how to find total element of string using python. The len() method to return the length of an string using python.
Here i will simple and easy example of how to get length of string in python. So let's see the below example:
Example 1 : using len()
# Python find string length
# using len
str = "nice snippets"
print(len(str))
Output:
13
Example 2 : using for loop
# Python find string length
# using for loop
# Returns length of string
def findLength(str):
counter = 0
for i in str:
counter += 1
return counter
str = "hello"
print(findLength(str))
Output:
5
Example 3 : using while loop
# Python find string length
# using while loop
# Returns length of string
def findLength(str):
counter = 0
while str[counter:]:
counter += 1
return counter
str = "nice snippets"
print(findLength(str))
Output:
13
Example 4 : using join and count
# Python find string length
# using join and count
# Returns length of string
def findLength(str):
if not str:
return 0
else:
some_random_str = 'py'
return ((some_random_str).join(str)).count(some_random_str) + 1
str = "snippets"
print(findLen(str))
Output:
8
It will help you....
#Python