This concise, example-based article will walk you through several different ways to find the length (the number of characters) of a given string in Python. Each approach will be explained briefly, followed by a code example. I assume that you already have some basic understanding of the programming language, so I won’t waste your time with meaningless words (like talking about the history of Python). Let’s get to the point!
Using the len() function (recommended)
len()
is a built-in function of Python. It returns the length of a string or any other iterable object.
Example:
text = "Welcome to Sling Academy"
length = len(text)
print(length)
Output:
24
In general, this one is the most simple, elegant, and efficient approach to getting the length of a Python string.
Using a for loop
By using a for
loop, you can iterate over the string and count the characters one by one.
Example:
my_string = "Fighting dragons is my hobby!"
length = 0
for letter in my_string:
length += 1
print(f"The length of my_string is {length}")
Output:
The length of my_string is 29
Using list comprehension
List prehension is a powerful and beautiful feature of Python that other popular programming languages like JavaScript or Dart do not have. You can take advantage of it to get the job done.
Example:
text = "He thrusts his fists against the posts and still insists he sees the ghosts"
length = len([char for char in text])
print(length)
Output:
75
Using recursion
A recursive function is a function that calls itself. We can implement a recursive function to count the length of a given string. This is like using something as big and expensive as a rocket to light a bonfire, but it will give you more solid muscles in programming with Python.
Example:
def get_length(text):
if text == "":
return 0
else:
return 1 + get_length(text[1:])
length = get_length("Sling Academy is a website for learning Python.")
print(length)
Output:
47
Using regular expressions
You can utilize the re
module to find the length of the string by matching all characters using a regular expression pattern. Even though it seems that this technique is much heavier than necessary, it’s worth knowing.
import re
text = "Welcome to slingacademy.com"
matches = re.findall(".", text)
length = len(matches)
print(length)
Output:
27
Using the reduce() function
The reduce()
function from the functools
module can be used to perform a cumulative operation on a sequence. In this case, we can use it, to sum up the characters in the string.
Example:
from functools import reduce
text = "No more boring foo-bar examples"
length = reduce(lambda count, char: count + 1, text, 0)
print(length)
Output:
31
Using a while loop
We can use a while
loop to count the number of characters in a given string by iterating through it until no more characters are left.
Example:
# Define a reusable function
def get_length(str):
count = 0
while str[count:]:
count += 1
return count
print(get_length("Goodbye World!"))
Output:
14
The tutorial ends here. Happy coding & enjoy your day!