2

How do I use the string format function to pre-pend a specified number of spaces to a string? Everything I search (e.g. this post and this post) tells me to use something like

"{:>15}".format("Hello")

But that will give me 10 spaces in front. What if I always want to put 4 spaces in front, keeping things left-aligned, when the input strings are of variable length? For example:

    Hello
    Goodbye

I thought of doing

"{:4}{}".format("", "Hello")

Which does work, but then I have to pass in this bogus empty string. Is there a cleaner way to achieve this?

adamconkey
  • 2,420
  • 3
  • 20
  • 50
  • 1
    simply adding 4 spaces in the formatted string does what you want ? `____{}".format(foo)` ( I had to put underscores as stackoverflow removes multiple spaces) – Taek Nov 29 '18 at 17:02
  • @Oniro but what if I wanted 13 spaces. I'm not going to sit there and count out 13 spaces. That is actually precisely what I'm trying to avoid. – adamconkey Nov 29 '18 at 17:04
  • 1
    You can try `f-strings`. Something like `f"{'':4}{'Hello'}"` – Srce Cde Nov 29 '18 at 17:05
  • 1
    sorry i misunderstood your question, `"{}{}".format(" "*n, foo)` will give you `n` spaces. – Taek Nov 29 '18 at 17:07

3 Answers3

0

This doesn't use format, but textwrap.indent() does what you want.

 >>> import textwrap
 >>> s = 'hello\n\n \nworld'
 >>> textwrap.indent(s, ' ' * 4)
 '    hello\n\n \n  world'

Python also allows you to define your own formatting options. See this question an example of how to override it. In this case, it might look like:

import string
import re

class Template(string.Formatter):
    def format_field(self, value, spec):
        if re.match('\d+t', spec):
            value = ' ' * int(spec[:-1]) + value
            spec = ''
        return super(Template, self).format_field(value, spec)

Usage:

>>> fmt = Template().format
>>> fmt('{:4t} {}', 'hello', 'world')
    hello world

Studying the format string language, I do not see a way to do exactly what you want.

0

If you have n as your number of spaces required

newString = f'{" "*n}oldstring'

should add n spaces

Josh
  • 65
  • 1
  • 8
0

You can use a helper function and define the number of spaces or type of indent you want:

def indent(word, n = 1, style = ' '):
    print(f"{style * n}->{word}")

indent('hello', n = 10)
>>          ->hello

indent('hello', n = 10, style = '*')
>>**********->hello

You can change the default value of the n keyword or style according to your needs so that you won't have to always have to use f-strings or format on every output.

BernardL
  • 4,161
  • 3
  • 24
  • 44