2015-05-14 61 views
2

我製作了一個使用*打印出形狀的功能。如何打印*爲水平的形狀?

我的代碼是

def print_saw(tooth_size, number_of_teeth): 
"""Print the saw drawing""" 
counter_2 = 0 
while counter_2 != number_of_teeth: 
    counter = 1 
    while counter != tooth_size+1: 
     print("*" * counter) 
     counter = counter + 1 
    counter_2 = counter_2 + 1 

有更多的代碼這一點。但是這是打印鋸的功能。這是像Python這樣打印。

>>> print_saw(4, 3) 
* 
** 
*** 
**** 
* 
** 
*** 
**** 
* 
** 
*** 
**** 

但我希望它打印水平。像這樣。

>>> print_saw(4, 3) 
* * * 
** ** ** 
*** *** *** 
************ 

回答

1

而不使用格式化的簡單方法:

def print_saw(size, number): 
    for s in range(size): 
     print(('*' * (s + 1) + ' ' * (size - s - 1)) * number) 

給出:

print_saw(5, 3) 
* * *  
** ** ** 
*** *** *** 
**** **** **** 
*************** 
+0

謝謝!工作很好 – Tribetter

0

您可以使用字符串格式設置每個「牙齒」的寬度,然後乘以牙齒的數量。

def print_saw(tooth_height, num_teeth, tooth_width=None): 
    if tooth_width is None: 
     tooth_width = tooth_height # square unless specified 
    for width in range(1, tooth_height+1): 
     row = "{{:<{}}}".format(tooth_width).format("*" * width) 
     print(row * num_teeth) 

DEMO:

In [2]: print_saw(6, 3) 
*  *  * 
** ** ** 
*** *** *** 
**** **** **** 
***** ***** ***** 
****************** 

In [3]: print_saw(4, 6, 5) 
* * * * * * 
** ** ** ** ** ** 
*** *** *** *** *** *** 
**** **** **** **** **** **** 

這是通過格式化兩次,第一次做:

>>> tooth_width = 6 
>>> row = "{{:{}}}".format(tooth_width) 
>>> row 
"{:6}" 

和對方完成:

>>> width = 3 
>>> row = row.format("*" * width) 
>>> row = "*** " 
True 

然後乘以通過你想要的牙齒數量爲

>>> num_teeth = 3 
>>> row * 3 
*** *** *** 
0

的代碼如下:「對每一行,印刷齒,所期望的重複這由擴展到齒寬的填充內容組成。「

def print_saw(size, reps, fill='*'): 
    for row in range(1, size + 1): 
     tooth = '{content:{width}}'.format(content=row * fill, width=size) 
     print(reps * tooth) 

更多的串聯和較少的字符串倍增的變體:

def print_saw(size, reps, fill='*'): 
    while len(fill) <= size: 
     print(reps * '{0:{width}}'.format(fill, width=size)) 
     fill += fill[0]