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.
This is fast, readable, and implemented efficiently in CPython.
It also works with longer strings, not only one character.
Handle Dynamic Inputs Safely
If n comes from user input or a file, validate it before multiplication.
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.
This style is helpful only when your list construction step already exists for other reasons.
For generated characters based on logic, comprehensions are reasonable.
If output has a fixed width with spaces or zeros, dedicated formatting is often better than manual repetition.
Unicode and Memory Considerations
String multiplication works with Unicode safely.
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.
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
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.
Use built-in padding methods when alignment is the main goal instead of manual repetition expressions.
Common Pitfalls
- Forgetting to validate negative
nwhen input is external. - Using complex
joinor 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
nis user-provided or business-critical. - Use
joinor 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.

