Skip to content
Home » String Length

String Length


String Length (Data Structure) — Using Python

A string in Python is a sequence of characters stored as an immutable data structure.
The length of a string refers to the number of characters it contains.

Example:

s = "HELLO"

Length → 5


⭐ 1. How Python Stores Strings Internally

  • Python strings are immutable objects.
  • Each string object internally stores:
    • Character array
    • Length of the string
    • Hash value (if computed)

Since length is precomputed, finding length is O(1) time.


⭐ 2. How to Find String Length in Python

Python provides a built-in function len():

s = "HELLO"
print(len(s))    # Output: 5

⭐ 3. Why len() is O(1) in Python?

In languages like C:

  • Strings are null-terminated
  • So length must be computed by scanning
  • Therefore strlen()O(n)

In Python:

  • Strings store their length in an internal attribute
  • len(s) simply returns that stored value
  • Therefore → O(1) (constant time)

This is important in data structure efficiency.


⭐ 4. Manual Length Calculation (Python Logic)

Even though Python’s len() is O(1), we can compute manually to understand the concept of iteration.

Example: Counting characters manually

def string_length(s):
    count = 0
    for _ in s:
        count += 1
    return count

print(string_length("HELLO"))  # Output: 5

Time Complexity:
[
O(n)
]

This simulates how languages like C calculate length.


⭐ 5. String Length With Spaces

Spaces, symbols, digits — all are counted:

s = "A B C"
print(len(s))   # Output: 5

Characters: A, space, B, space, C → 5 characters


⭐ 6. Unicode & Emoji Length in Python

Python strings support Unicode.

Example:

print(len("😊"))    # Output: 1

Although emoji may take multiple bytes internally, Python counts it as 1 character.


⭐ 7. Practical Examples

A. Count number of characters in a user input

s = input("Enter string: ")
print("Length =", len(s))

B. Count letters without spaces

s = "Hello World"
length_without_spaces = len(s.replace(" ", ""))
print(length_without_spaces)   # Output: 10

⭐ 8. String Length Applications in Data Structures

String length is used in:

  • Pattern matching algorithms (KMP, Rabin–Karp)
  • Text processing
  • Tokenization in compilers
  • Data compression
  • Hashing
  • Substring calculations
  • File parsing
  • Natural Language Processing (NLP)

⭐ 9. Summary (Exam-Ready Notes)

✔ A string is a sequence of characters.
✔ Python stores strings as immutable objects and stores their lengths internally.
len(s) returns string length in O(1) time.
✔ Manual length calculation uses iteration → O(n).
✔ Python correctly counts Unicode characters and emojis.