How To Get The Length Of A String In Python?

Get the length of a String in Python

There are some methods we have effectively tested to get the length of a string in Python. Follow the article to better understand.

What is the length of a String in Python?

The length of a string is the number of characters that make up the string. Example: I have a string “learnshareit”. You can also easily count the number of characters inside this string as 12.

Note: the string length is different from the internal index. The most extensive index in the string is equal to the length minus 1 unit.

Get the length of a string in Python

Use len() method 

You can use the len() function to get the length of string. Len() is a built-in function that counts the number of characters in the argument. The argument passed to the function can be a string or a list.

Syntax:

len(str)

Parameters:

  • str: string to find the length.

Example:

  • Create a string.
  • Use the len() function to get the string length.
myStr = "hello! My name is John. I am 28. My current job is a developer"

# Use the len() function to get the string length
result = len(myStr)
print("The number of characters in the string is:", result)

Output:

The number of characters in the string is: 62

Use For loop

If you don’t want to use the len() function, then you can use a for loop to count the number of characters in the string.

Example:

  • Create a string.
  • Use the for loop to get the string length.
myStr = "hello! My name is John. I am 28. My current job is a developer"

# Create counter variable.
n = 0

# Use for loop.
for i in myStr:
    n += 1

print("The number of characters in the string is:", n)

Output:

The number of characters in the string is: 62

After each iteration through the string, the variable ‘n’ will increase by one until the end.

Use the length_hint() function

In Python ‘operator’ module has a built-in length_hint() function. The length_hint() function returns the length for the ‘obj’ object.

Syntax:

length_hint(obj)

Parameters:

  • object: can be string, list, dict, tuple, etc.

Note: Declare the operator module before using the function.

Example:

  • Create a string.
  • Use the length_hint() function to get the string length.
from operator import length_hint
 
myString = ("hello! My name is John. I am 28. My current job is a developer")

# Use the length_hint() function to get the string length
result = length_hint(myString)
print ("The number of characters in the string is:", result) 

Output:

The number of characters in the string is: 62

Summary

Please leave a comment below if you have any questions about this article. I will support your questions.
Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *