How to print right justify string?

时间:2018-02-03 10:39:19

标签: python python-3.x

I am trying to write a program that print the tree right justified. Here's my code:

height = int(input("Enter height of a tree: "))
for a in range(height + 1):
    for b in range(a):
        print("*", end="")  
    print()
for c in reversed(range(a)):
    for d in range(c):
        print("*", end="")
    print()

But currently it print the left justified tree. I want to justify the strings to right.

So instead of looking like this: For instance, input = 2

*
**
*

Would look like that:

  *
 **
  *

Can't figure out the proper logic

1 个答案:

答案 0 :(得分:0)

You should be using str.rjust to right justify your string. For example

>>> '*'.rjust(5)
'    *'

Using this, you may create your function as:

def print_tree(height):
    half_height = int((height+1)/2)
    for i in range(1, height+1):
        if i <= half_height:
            print(('*'*i).rjust(half_height))
        else:
            print(('*'*(height-i+1)).rjust(half_height))

Sample Run:

>>> print_tree(5)
  *
 **
***
 **
  *
>>> print_tree(4)
 *
**
**
 *
>>> print_tree(3)
 *
**
 *