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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 11 views 0 copies

Python code

21 lines
Python 3.9+
def 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

stdout
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

  1. Use `sep.join(s for _ in range(n))` with a generator, though building a list is usually fine for small n.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.