Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Retain first N Elements of a String and Replace the Remaining by K
In this article, we will learn how to retain the first N characters of a string and replace the remaining characters with a specified character K. Python provides several built-in functions like len(), slicing, replace(), and ljust() to accomplish this task efficiently.
Problem Overview
Given an input string, we need to keep the first N characters unchanged and replace all remaining characters with a replacement character K.
Example
Let's understand this with a simple example ?
# Input
input_string = 'tutorialspoint'
n = 9
k = "#"
# Expected output: 'tutorials#####'
print(f"Original: {input_string}")
print(f"Keep first {n} chars, replace rest with '{k}'")
Original: tutorialspoint Keep first 9 chars, replace rest with '#'
In this example, the first 9 characters 'tutorials' are retained, and the remaining 5 characters are replaced with '#' symbols.
Method 1: Using Slicing and Multiplication Operator
This approach uses string slicing to extract the first N characters and the multiplication operator to create replacement characters ?
def retain_and_replace_v1(input_string, n, k):
# Slice first N characters + multiply K by remaining length
return input_string[:n] + k * (len(input_string) - n)
# Example usage
input_string = 'tutorialspoint'
n = 9
k = "#"
result = retain_and_replace_v1(input_string, n, k)
print(f"Input string: {input_string}")
print(f"Result: {result}")
Input string: tutorialspoint Result: tutorials#####
Method 2: Using ljust() Function
The ljust() method left-aligns the string and pads it with a specified character ?
def retain_and_replace_v2(input_string, n, k):
# Slice first N characters, then use ljust to pad with K
return input_string[:n].ljust(len(input_string), k)
# Example usage
input_string = 'tutorialspoint'
n = 9
k = "#"
result = retain_and_replace_v2(input_string, n, k)
print(f"Input string: {input_string}")
print(f"Result: {result}")
Output: tutorialspoint Result: tutorials#####
Method 3: Using replace() Function
This method uses replace() to substitute the remaining characters with the replacement character ?
def retain_and_replace_v3(input_string, n, k):
# Replace the substring after N with K characters
remaining_part = input_string[n:]
replacement = k * len(remaining_part)
return input_string.replace(remaining_part, replacement)
# Example usage
input_string = 'tutorialspoint'
n = 9
k = "#"
result = retain_and_replace_v3(input_string, n, k)
print(f"Input string: {input_string}")
print(f"Result: {result}")
Input string: tutorialspoint Result: tutorials#####
Comparison of Methods
| Method | Approach | Readability | Performance |
|---|---|---|---|
| Slicing + Multiplication | String concatenation | High | Best |
| ljust() | Left-justify with padding | High | Good |
| replace() | String replacement | Medium | Good |
Complete Example with Error Handling
def retain_and_replace(input_string, n, k):
"""Retain first N characters and replace remaining with K"""
if n >= len(input_string):
return input_string # No replacement needed
return input_string[:n] + k * (len(input_string) - n)
# Test with different inputs
test_cases = [
('tutorialspoint', 9, '#'),
('python', 3, '*'),
('hello', 10, '-'), # N greater than string length
]
for string, n, k in test_cases:
result = retain_and_replace(string, n, k)
print(f"'{string}' (N={n}, K='{k}') ? '{result}'")
'tutorialspoint' (N=9, K='#') ? 'tutorials#####' 'python' (N=3, K='*') ? 'pyt***' 'hello' (N=10, K='-') ? 'hello'
Conclusion
We explored three different methods to retain the first N characters of a string and replace the remaining with a specified character. The slicing with multiplication operator approach is the most efficient and readable solution for this task.
