Repeat a string n times with a separator in Python
Repeats a string a given number of times, joining the repetitions with an optional separator, with a guard for non-positive counts.
Python code
21 linesdef repeat_string_with_separator(s, n, sep=''):
"""
Repeats a string n times, joining with a separator.
Args:
s (str): The string to repeat.
n (int): Number of repetitions.
sep (str): Separator between repetitions (default: '').
Returns:
str: The repeated string.
"""
if n <= 0:
return ''
return sep.join([s] * n)
if __name__ == "__main__":
print(repeat_string_with_separator("ha", 5, "-"))
print(repeat_string_with_separator("abc", 3, ", "))
print(repeat_string_with_separator("x", 2))
print(repeat_string_with_separator("hello", 0, "|"))
Output
ha-ha-ha-ha-ha
abc, abc, abc
xx
How it works
The function repeat_string_with_separator builds a list [s] * n where n is the repeat count, then passes that list to str.join(). The separator sep is inserted between every pair of repetitions, not at the ends. The guard if n <= 0 returns an empty string so you never get trailing separators or confusing negative repeats. This approach is concise, readable, and avoids manual loops or accumulating strings with +=, which would be slower for large counts.
Common mistakes
- Forgetting the guard for n <= 0 could yield a separator even with zero repeats, e.g., returning '-' instead of ''.
- Using `s * n + sep` for all but the last repetition, which adds an extra separator at the end.
- Assuming `sep` defaults to a space; the default is an empty string, so repeated strings are concatenated directly.
Variations
- Use `sep.join(s for _ in range(n))` with a generator, though building a list is usually fine for small n.
- For simple concatenation without separators, use the built-in `s * n` operator.
Real-world use cases
- Building a comma-separated list of user IDs or filenames for a logging message.
- Creating repeated delimiter-separated patterns, like dashes for visual dividers in a report.
- Generating test data, such as repeating a payload string for synthetic load tests.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.