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
  • 750
  • 5
  • 19

3 Answers3

3

You may use str.format as:

>>> space_count = 10
>>> '{}{}'.format(' '*space_count, 'Hello')
'          Hello'
#^^^^^^^^^^
#1234567890 spaces
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
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
  • 12,086
  • 10
  • 64
  • 109
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
  • 4,299
  • 5
  • 32
  • 50
DiveIntoML
  • 2,347
  • 2
  • 20
  • 36