## Problem Formulation

- Given a Python string
`s`

with length`k<=n`

. - How to fill the string with
`n-k`

empty spaces on the left so that the new string has length`n`

?

Here are some examples:

INPUT: 'a', n = 2OUTPUT: 'a 'INPUT: 'hi', n = 4OUTPUT: 'hi 'INPUT: 'hi', n = 2OUTPUT: 'hi'INPUT: 'finxter', n = 10OUTPUT: 'finxter '

## Method 1: str.ljust()

The built-in Python `str.ljust(length, fillchar)`

method returns a left-justified string by appending fill characters up to a certain length. Per default, `fillchar`

is set to the empty space, so `str.ljust(n)`

creates a new string by appending empty spaces up to length `n`

.

Here’s the method applied to our four examples:

>>> 'a'.ljust(2) 'a ' >>> 'hi'.ljust(4) 'hi ' >>> 'hi'.ljust(2) 'hi' >>> 'finxter'.ljust(10) 'finxter '

You can learn more about the string method `ljust()`

here:

## Method 2: Literal String Interpolation Left Justify

Literal string interpolation is a relatively new Python feature that introduces f-strings that are string literals prefixed by the letter `'f'`

or `'F'`

and with special functionality. For example, you can left-justify a string using `'{variable:<n}'`

where `n`

is the desired length.

Here’s how this works out for our examples: ??

# Example 1 >>> s = 'a' >>> f'{s:<2}' 'a ' # Example 2 >>> s = 'hi' >>> f'{s:<4}' 'hi ' # Example 3 >>> f'{s:<2}' 'hi' # Example 4 >>> s = 'finxter' >>> f'{s:<10}' 'finxter '

## Method 3: Literal String Interpolation Space Padding

F-strings also provide you a simple means to use padding on a string with the expression `'{variable:n}'`

where `n`

is the desired length. Python then fills up the string with empty spaces.

Here’s how this works out for our examples: ??

# Example 1 >>> s = 'a' >>> f'{s:2}' 'a ' # Example 2 >>> s = 'hi' >>> f'{s:4}' 'hi ' # Example 3 >>> f'{s:2}' 'hi' # Example 4 >>> s = 'finxter' >>> f'{s:10}' 'finxter '

I would say this is even prettier than ** Method 2** due to its conciseness and clarity. 🙂

If you need some refreshing on F-Strings, feel free to check out our detailed guide on the Finxter blog.

## Method 4: String Concatenation

A simple way without f-strings to fill a given string with empty spaces to obtain a left-justified string is to use string concatenation arithmetic via the overloaded `+`

and `*`

operators. For example, the expression `s + ' ' * n-k`

appends `n-k`

empty spaces to the string `s`

.

Here’s the code on our examples:

# Example 1 >>> s = 'a' >>> n = 2 >>> s + ' ' * (n - len(s)) 'a ' # Example 2 >>> s = 'hi' >>> n = 4 >>> s + ' ' * (n - len(s)) 'hi ' # Example 3 >>> n = 2 >>> s + ' ' * (n - len(s)) 'hi' # Example 4 >>> s = 'finxter' >>> n = 10 >>> s + ' ' * (n - len(s)) 'finxter '

## Summary

There are four ways to fill a string with `n-k`

empty spaces on the left so that the new string has length `n=10`

.

- Left justification –
`s.ljust(10)`

- F-strings with left justification –
`f'{s:<10}'`

- F-strings with padding –
`f'{s:10}'`

- String arithmetic –
`s + ' ' * (n - len(s))`

There are two types of people, those who love and frequently use smart Python one-liners like those ones—and those that don’t understand them. For both, I’ve written the book Python One-Liners which took me a year of dedicated effort and thousands of hours of work.

I’d love to show you all I know about short and concise Python code in my book from the best-selling Python book publisher NoStarch:

## Python One-Liners Book: Master the Single Line First!

**Python programmers will improve their computer science skills with these useful one-liners.**

*Python One-Liners* will teach you how to read and write “one-liners”: ** concise statements of useful functionality packed into a single line of code. **You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce ** key computer science concepts **and

**. You’ll learn about advanced Python features such as**

*boost your coding and analytical skills**,*

**list comprehension****,**

*slicing***,**

*lambda functions***,**

*regular expressions***and**

*map***functions, and**

*reduce***.**

*slice assignments*You’ll also learn how to:

- Leverage data structures to
**solve real-world problems**, like using Boolean indexing to find cities with above-average pollution - Use
**NumPy basics**such as*array*,*shape*,*axis*,*type*,*broadcasting*,*advanced indexing*,*slicing*,*sorting*,*searching*,*aggregating*, and*statistics* - Calculate basic
**statistics**of multidimensional data arrays and the K-Means algorithms for unsupervised learning - Create more
**advanced regular expressions**using*grouping*and*named groups*,*negative lookaheads*,*escaped characters*,*whitespaces, character sets*(and*negative characters sets*), and*greedy/nongreedy operators* - Understand a wide range of
**computer science topics**, including*anagrams*,*palindromes*,*supersets*,*permutations*,*factorials*,*prime numbers*,*Fibonacci*numbers,*obfuscation*,*searching*, and*algorithmic sorting*

By the end of the book, you’ll know how to ** write Python at its most refined**, and create concise, beautiful pieces of “Python art” in merely a single line.

*Get your Python One-Liners on Amazon!!*

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.