String को Specific Length तक Repeat करना
यदि आप String को n Characters तक Repeat करना चाहते हैं, तो आप पहले Whole String को n/len(s) Times Repeat कर सकते हैं और अंत में n%len(s) Characters Add कर सकते हैं।
उदाहरण 1: Manual Calculation
def repeat_n(string, n):
l = len(string)
full_rep = n // l
# Full Repetitions के साथ String Construct करें
ans = ''.join(string for i in range(full_rep))
# अंत में Remaining Characters Add करें
return ans + string[:n % l]
repeat_n('asdf', 10)
# Output: 'asdfasdfas'
उदाहरण 2: Multiplication Operator का उपयोग (Simpler)
def repeat_n(string_to_expand, n):
return (string_to_expand * ((n // len(string_to_expand)) + 1))[:n]
repeat_n('asdf', 10)
# Output: 'asdfasdfas'
उदाहरण 3: itertools.cycle का उपयोग (Memory Efficient)
from itertools import cycle, islice
def repeat_n(string, n):
return ''.join(islice(cycle(string), n))
repeat_n('asdf', 10)
# Output: 'asdfasdfas'
Comparison:
| Method | Pros | Cons |
|---|---|---|
| Multiplication + Slice | Simple, Fast, Readable | Temporary Large String बनाता है |
| itertools.cycle + islice | Memory Efficient, Lazy | Slightly Slower |
| Manual Loop | Full Control | Verbose, Slower |
Recommendation:
अधिकांश Cases के लिए Multiplication + Slice Method सबसे अच्छा Balance प्रदान करता है Simplicity और Performance का।