Jump to content

How Do You Find the Length of String in Python

Linux Hint

Recommended Posts

Python is a popular language that provides various functions to manipulate strings. While working with strings, we may need to find the length of strings. For that, there are different methods in Python. This article will cover various ways of finding the length of string in Python.

Using the len() function

The len() function in Python is the easiest and most direct way of determining string length. This function outputs the total count of characters in an input string. Here’s an example:

string = "Hello, world!"

length = len(string)

print("Length:", length)

The output will be:


Using the for Loop

Another approach to finding the length of a string is by iterating through its characters. We can use a loop to iterate through each character until we reach the end of the string, incrementing a counter along the way. Here’s an example:

string = "Hello, world!"

count = 0

for char in string:

count += 1

print("Length:", count)

The output will be the same as before: 13. However, using For loop is considered less efficient than using the len() function because it involves manual iteration.

A picture containing text, screenshot Description automatically generated

Measuring the Length Using Regular Expressions

Regular expressions can manipulate and search for patterns within strings. Although using regular expressions to find the length of a string may not be the most efficient method, it can provide additional flexibility if there are specific requirements. Here’s an example:

import re

string = "Hello, world!"

length = len(re.findall(".", string))

print("Length:", length)

The output will be 13, just like the previous methods. However, regular expressions are better suited for complex pattern-matching tasks rather than simple length calculations.

A picture containing text, white, font, screenshot Description automatically generated


In Python, we have numerous ways of finding the length of a string in Python. The len() function is the simplest way of finding the length of a string in Python. However, we can also find the length of a string in Python by iterating through the string. There is another way of finding the length of the string is by using Regular expressions. All three methods are discussed here. Read for more details.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...