Index Mapping Cypher in Python

The Index Mapping Cipher is a technique that extracts characters from a string using digits as indices. Each digit in the index number corresponds to a position in the original string, creating a new string based on these mapped positions.

How It Works

Given a string and an index number, each digit of the index represents a position in the string ?

# Example: "HELLO" with index 1043
# Digit 1 ? H[1] = 'E'  
# Digit 0 ? H[0] = 'H'
# Digit 4 ? H[4] = 'O'
# Digit 3 ? H[3] = 'L'
# Result: "EHOL"

original = "HELLO"
index = 1043
result = ""

for digit in str(index):
    pos = int(digit)
    if pos < len(original):
        result += original[pos]
        
print(f"Original: {original}")
print(f"Index: {index}")  
print(f"Result: {result}")
Original: HELLO
Index: 1043
Result: EHOL

Method 1: Using For Loop

This approach iterates through each digit and maps it to the corresponding character ?

def index_mapping_cipher(text, index):
    result = ""
    for digit in str(index):
        pos = int(digit)
        if pos < len(text):
            result += text[pos]
    return result

# Example
text = "TUTORIALSPOINT"
index = 6875
result = index_mapping_cipher(text, index)

print(f"Original string: {text}")
print(f"Index value: {index}")
print(f"Mapped result: {result}")
Original string: TUTORIALSPOINT
Index value: 6875
Mapped result: ASLI

Method 2: Using List Comprehension

A more concise approach using list comprehension with join() ?

# Create the string
text = "BROWSER"
index = "4154"

# List comprehension approach
result = ''.join([text[int(digit)] for digit in index if int(digit) < len(text)])

print(f"Original string: {text}")
print(f"Index value: {index}")
print(f"Mapped result: {result}")
Original string: BROWSER
Index value: 4154
Mapped result: SRES

Method 3: Reverse Index Mapping

This variation processes the index digits in reverse order ?

def reverse_index_mapping(text, index):
    result = ""
    # Process digits in reverse order
    for digit in str(index)[::-1]:
        pos = int(digit)
        if pos < len(text):
            result += text[pos]
    return result

# Example
text = "INTERSTELLAR"
index = 7455
result = reverse_index_mapping(text, index)

print(f"Original string: {text}")
print(f"Index value: {index}")
print(f"Reverse mapped result: {result}")
Original string: INTERSTELLAR
Index value: 7455
Reverse mapped result: SSRE

Comparison

Method Readability Performance Best For
For Loop High Good Clear logic flow
List Comprehension Medium Better Concise code
Reverse Mapping High Good Special cipher variants

Conclusion

Index Mapping Cipher is useful in cryptography and data encoding. Use list comprehension for concise implementation or for loops when clarity is important. Always validate indices to avoid index errors.

Updated on: 2026-03-27T12:15:56+05:30

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements