0

I am trying to have a user input a word and a certain number of spaces before it: e.g. if the user wants 10 spaces before a word it will print:

..........foo

But without the .'s (That's just to make it clear that there is ten spaces here!). How would I go about doing this?

Jacob
  • 101
  • 7
  • 2
    checkout [How can I fill out a Python string with spaces?](http://stackoverflow.com/questions/5676646/how-can-i-fill-out-a-python-string-with-spaces) – davedwards Dec 21 '16 at 19:59
  • 1
    How about `10 * " " + "foo"`... Or more generally: `n_spaces * " " + ` – blacksite Dec 21 '16 at 20:03
  • @JimFasarakisHilliard: Dupe question is related to filling up the spaces for constant width of OVERALL string. But here OP want the count of space as constant – Anonymous Dec 21 '16 at 20:38

3 Answers3

3

You may use str.format as:

>>> space_count = 10
>>> '{}{}'.format(' '*space_count, 'Hello')
'          Hello'
#^^^^^^^^^^
#1234567890 spaces
Anonymous
  • 40,020
  • 8
  • 82
  • 111
1

As I alluded to in the comments, you can define a function to add any number of spaces to the left of your string:

def add_spaces(n_spaces, string):
    return " " * n_spaces + string

Test it out:

>>> add_spaces(10, "foo")
'          foo'
blacksite
  • 10,028
  • 6
  • 44
  • 94
0

Let's say your string is x="foo", and you have pad=10 indicating the number of spaces you want to pad to the left.

Then you can use "format" method for strings in Python in the following way:

("{:>%d}" %(len(x)+pad)).format(x)

It is basically the same as "{:>13}".format(x), indicating you want to right align x within a total length of 13 by padding spaces between x.

Will
  • 3,611
  • 5
  • 26
  • 47
DiveIntoML
  • 1,624
  • 1
  • 15
  • 27