Skip to content
  • (+91) 9409548155
  • support@appdividend.com
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Menu
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
  • Home
  • Pricing
  • Instructor
  • Tutorials
    • Laravel
    • Python
    • React
    • Javascript
    • Angular
  • Become A Tutor
  • About Us
  • Contact Us
Python

How to Find the Length of a String in Python

  • 21 Feb, 2025
  • Com 0
Python String Size

Python provides a built-in len() function that returns the number of characters (including spaces and punctuation) in a string, which is also the string’s length.

Python len() function for string

 

new_string = 'Leo Messi'

length_of_string = len(new_string)

print("Length of the string:", length_of_string)

# Output: Length of the string: 9

Strings are built from characters, and each character has a fixed length. Finding the length of a string means how many characters are in the string.

You must count each character, including spaces and punctuation, so even if the string has spaces like “hello world”, the number of characters would be 11 because there’s a space between the two words.

Empty String

If a string is empty, the length of that string is 0.

str = ""

print(len(str))

# Output: 0

Special Characters, like emojis or Unicode characters

If your string contains special characters like emojis (😊), that’s a single Unicode character. The len(😊) should return 1 because, in Python3, strings are Unicode by default.

str = "😊"

print(len(str))

# Output: 1

However, some Unicode characters are a combination of multiple code points. For example, some emojis are combinations, like flags or skin tone modifiers, or 👨🏾🚀. How about that?

If I have a string with a combined emoji, like “👨🏾🚀”, which represents an astronaut with a specific skin tone, it can have multiple code points, depending on its representation.

str = "👨🏾🚀"

print(len(str))

# Output: 3

You thought there were only two characters, but no, there are 3. That means counting characters might become complicated when using emojis.

Escape Characters

Your input string may contain escape characters like “\n” or newline characters. How will len() function judge that? Well, it will count as a single character. A string can have multiple escape characters.

str = "Hello\tWorld\n"

print(str)
# Output: Hello 	World

print(len(str))
# Output: 12

Here, \t is counted as one character, and \n is counted as one character. Two special characters. The other 10 are regular characters. Hence, the total length is 12.

Alternate Approaches

Here are three alternate ways:

  1. Using List Comprehension
  2. Using reduce()
  3. Using a for loop

Approach 1: Using List Comprehension

The combination of List comprehension with the sum() function can iterate over the string and generate a sequence of 1s, one for each character. The sum of this sequence provides the total length of the string.

Using List Comprehension

new_string = 'Leo Messi'

length_of_string = sum(1 for _ in new_string)

print("Length of the string:", length_of_string)

# Output: Length of the string: 9

Approach 2: Using reduce()

The reduce() function, combined with a lambda function, iterates over the string, incrementing a counter for each character encountered, and the final counter will be the size of the string.

Using reduce() function

from functools import reduce

new_string = 'Leo Messi'

length_of_string = reduce(lambda count, _: count + 1, new_string, 0)

print("Length of the string:", length_of_string)

# Output: Length of the string: 9

Approach 3: Using a for loop

A for loop iterates over each character in the string, incrementing the count variable by 1 for each character.

new_string = 'Leo Messi'

count = 0
for x in new_string:
    count += 1

print("Length of the string:", count)

# Length of the string: 9

Why do we measure the size of a string?

Data validation

To validate an input field, such as a username or password, you first need to determine its size. To do this, you can use the len() function.

username = input("Enter username: ")

if 3 <= len(username) <= 20:
    print("Valid username")
else:
    print("Username must be 3-20 characters")

# Output:
# Enter username: de
# Username must be 3-20 characters

Check for an empty input

If you want to ensure that your input is not empty, you should create an if condition based on its length and compare it to 0.

user_input = input("Enter text: ").strip()

if len(user_input) == 0:
    print("Input cannot be empty!")

# Output:
# Enter text:
# Input cannot be empty!

Encryption/Hashing

You can create a hashed or encrypted string by determining its length and padding some characters to hash it.

def pad_string(str, block_size):
    return str + '0' * (block_size - len(str) % block_size)


original = "kaynes"
padded = pad_string(original, 8)

print(padded)
# Output: kaynes00

That’s all!

Post Views: 46
Share on:
Krunal Lathiya

With a career spanning over eight years in the field of Computer Science, Krunal’s expertise is rooted in a solid foundation of hands-on experience, complemented by a continuous pursuit of knowledge.

How to Create and Download Zip File in Laravel 11
How to Get the Length of an Integer in Python

Leave a Reply Cancel reply

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

Address: TwinStar, South Block – 1202, 150 Ft Ring Road, Nr. Nana Mauva Circle, Rajkot(360005), Gujarat, India

Call: (+91) 9409548155

Email: support@appdividend.com

Online Platform

  • Pricing
  • Instructors
  • FAQ
  • Refund Policy
  • Support

Links

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of services

Tutorials

  • Angular
  • React
  • Python
  • Laravel
  • Javascript
Copyright @2024 AppDividend. All Rights Reserved
Appdividend