1

I have created a program.Here I need to leave some space and print an String after the spaces.I did that program with format in python.my code is below,

name = "myname"
print("{0:>10}".format(name))
#output="    myname"

Here, the sum of empty spaces and the length of name is equals to 10.I have declared the size inside print. But I need to declare the size as a variable.I tried it like this,

num = 10
name = "myname"
print("{0:>num}".format(name))

but it did not worked.I need to know how I can fix this.I need to take the same output with giving the size with an variable.please help...

Jeewantha Lahiru
  • 324
  • 2
  • 4
  • 15

2 Answers2

1

Try:

num = 10
name ="myname"
print(" "*num,name)

Or you can also do it via:

name ="myname"
print('{0} {1}'.format(' '*num,name))
Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
1

Try this one:

num_of_spaces = 10
name = "myname"
name.rjust(num_of_spaces) 
Gabio
  • 9,126
  • 3
  • 12
  • 32
  • This answer definitely produces the expected output. But since OP is already using string formatting, it's just a matter of adding another arg. (didn't downvote btw) See the dupe for more – yatu Apr 10 '20 at 09:49
  • @yatu IMHO one of the best things SO suggests is to learn different approaches to solve your problem. Since there was already a solution with string formatting, I wanted to share another way to tackle the OP's problem. – Gabio Apr 10 '20 at 09:53
  • Sure no one denies that. Just saying OP might find a small tweak to his current solution more helpful. But sure, sharing different equally or improved approaches is always a good thing – yatu Apr 10 '20 at 09:57
  • Hmm, maybe the reason I mentioned? Couldn't tell – yatu Apr 10 '20 at 09:58
  • But the solution with string formatting was already posted (by you if I am not mistaken). Why not to add another solution? never mind... – Gabio Apr 10 '20 at 10:01
  • I'm not disagreeing with you as I've told you. IMO it's not good enough of a reason to downvote this. Wasn't me who did – yatu Apr 10 '20 at 10:02