Python
string manipulation
code snippet
one-liner
programming tips

In Python, how do I create a string of n characters in one line of code?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a string with n repeated characters is a common Python task in padding, test-data generation, and formatting utilities. The one-line solution is usually simple, but edge cases such as negative lengths and multi-character patterns can change behavior. This guide covers practical one-liners and when each option is appropriate.

The Standard One-Liner

For a single repeated character, use string multiplication.

python
n = 8
s = "*" * n
print(s)  # ********

This is fast, readable, and implemented efficiently in CPython.

It also works with longer strings, not only one character.

python
token = "ab"
print(token * 4)  # abababab

Handle Dynamic Inputs Safely

If n comes from user input or a file, validate it before multiplication.

python
1def repeat_char(ch: str, n: int) -> str:
2    if len(ch) != 1:
3        raise ValueError("ch must be one character")
4    if n < 0:
5        raise ValueError("n must be non-negative")
6    return ch * n
7
8print(repeat_char("#", 5))

Python returns an empty string for negative multipliers in many cases, but explicit validation is clearer for business logic and API contracts.

Alternative One-Liners and Tradeoffs

You can build repeated strings using join, but this is usually less direct for pure repetition.

python
n = 5
s = "".join(["x"] * n)
print(s)

This style is helpful only when your list construction step already exists for other reasons.

For generated characters based on logic, comprehensions are reasonable.

python
n = 10
s = "".join("A" if i % 2 == 0 else "B" for i in range(n))
print(s)  # ABABABABAB

If output has a fixed width with spaces or zeros, dedicated formatting is often better than manual repetition.

python
value = 42
print(f"{value:06d}")  # 000042

Unicode and Memory Considerations

String multiplication works with Unicode safely.

python
print("λ" * 6)

For very large n, remember that full strings are allocated in memory. If you only need streaming output, write chunks instead of building one giant string.

python
1def stream_repeat(ch: str, n: int, chunk_size: int = 10000):
2    remaining = n
3    while remaining > 0:
4        m = min(remaining, chunk_size)
5        yield ch * m
6        remaining -= m
7
8for chunk in stream_repeat("x", 25000):
9    pass  # write chunk to file/socket

This pattern avoids large peak memory usage in batch jobs.

Common Practical Patterns

A few everyday examples where one-line repetition is useful:

  • Divider lines in CLI tools
  • Masking output such as * repeated by secret length
  • Generating test payloads quickly
  • Left or right padding helpers
python
1def mask(secret: str) -> str:
2    return "*" * len(secret)
3
4print(mask("topsecret"))

These patterns stay clean when repetition logic is isolated in small functions.

One-Liner for Padding Helpers

A frequent real-world use is fixed-width padding around existing text.

python
name = "cat"
padded = name.ljust(8, ".")
print(padded)  # cat.....

Use built-in padding methods when alignment is the main goal instead of manual repetition expressions.

Common Pitfalls

  • Forgetting to validate negative n when input is external.
  • Using complex join or loops when simple multiplication is enough.
  • Repeating multi-character strings unintentionally when one character was expected.
  • Building huge strings in memory when chunked output is more appropriate.
  • Mixing repetition and formatting concerns in one unreadable expression.

Summary

  • The best one-liner for repeated characters is ch * n.
  • Validate inputs when n is user-provided or business-critical.
  • Use join or comprehensions only for logic-based string generation.
  • Keep memory usage in mind for very large outputs.
  • Wrap repetition in small helpers to keep application code clear.

Course illustration
Course illustration

All Rights Reserved.