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 - Repeat String till K
In Python, you often need to repeat a string to reach a specific length. This is useful for padding, formatting, or creating patterns. Python provides several approaches: string multiplication, while loops, itertools, and list comprehension.
Using String Multiplication
The most efficient method uses string multiplication and slicing to achieve the exact length ?
def repeat_string(text, target_length):
# Calculate how many complete repetitions we need
full_repeats = target_length // len(text)
# Calculate remaining characters needed
remaining_chars = target_length % len(text)
# Create final string by repeating and adding partial string
result = text * full_repeats + text[:remaining_chars]
return result
original = "Hello"
length = 18
repeated = repeat_string(original, length)
print(f"Result: {repeated}")
print(f"Length: {len(repeated)}")
Result: HelloHelloHelloHel Length: 18
Using While Loop
A while loop keeps adding the string until the target length is reached ?
def repeat_with_loop(text, target_length):
result = ""
while len(result) < target_length:
result += text
# Trim to exact length
return result[:target_length]
original = "ABC"
length = 10
repeated = repeat_with_loop(original, length)
print(f"Result: {repeated}")
print(f"Length: {len(repeated)}")
Result: ABCABCABCA Length: 10
Using Itertools
The itertools module provides cycle() for infinite repetition and islice() to limit the length ?
import itertools
def repeat_with_itertools(text, target_length):
# cycle() creates infinite iterator, islice() limits it
repeated_chars = itertools.islice(itertools.cycle(text), target_length)
return ''.join(repeated_chars)
original = "XY"
length = 15
repeated = repeat_with_itertools(original, length)
print(f"Result: {repeated}")
print(f"Length: {len(repeated)}")
Result: XYXYXYXYXYXYXYX Length: 15
Performance Comparison
| Method | Speed | Memory Usage | Best For |
|---|---|---|---|
| String Multiplication | Fastest | Low | Most cases |
| While Loop | Slower | Medium | Learning/understanding |
| Itertools | Medium | Low | Large strings |
Practical Example
Creating a progress bar with repeated characters ?
def create_progress_bar(progress_percent, bar_length=20):
filled_length = int(bar_length * progress_percent / 100)
bar_char = "?"
empty_char = "?"
# Repeat characters to create progress bar
filled_bar = bar_char * filled_length
empty_bar = empty_char * (bar_length - filled_length)
return f"[{filled_bar}{empty_bar}] {progress_percent}%"
# Test different progress levels
for progress in [25, 50, 75, 100]:
print(create_progress_bar(progress))
[????????????????????] 25% [????????????????????] 50% [????????????????????] 75% [????????????????????] 100%
Conclusion
String multiplication is the most efficient method for repeating strings to a target length. Use itertools for memory-efficient handling of very large strings, and while loops when you need more control over the repetition process.
