2017-07-31 26 views
3

連接字符串當我運行這段代碼就如期望的那樣:Python的 - 用空格

x = int(input("Put number: ")) 
result_figure =[] 
xtempleft = x-1 
xtempright = 0 
space = " " 
sl = "/" 
bsl = "\\" 
#Q1 
for i in range(x): 
    if xtempleft > 0: 
     q1= space * xtempleft + sl 
     xtempleft -= 1 
     print(q1) 

    else: 
     q1 = sl 
     print(q1) 
#Q2 
for i in range(x): 
    if xtempright == 0: 
     xtempright += 1 
     q2= bsl 
     print(q2) 
    else: 
     q2 = space * xtempright + bsl 
     xtempright += 1 
     print(q2) 

我得到這個:

/
/
/
/
/
\ 
\ 
    \ 
    \ 
    \ 

的問題是,當我嘗試做一些修改:

for i in range(x): 
    result ="" 
    if xtempleft > 0: 
     q1= space * xtempleft + sl 
     xtempleft -= 1 
     result += q1  
    else: 
     q1 = sl 
     result += q1 
#Q2 
    if xtempright == 0: 
     xtempright += 1 
     q2= bsl 
     result += q2 
    else: 
     q2 = space * xtempright + bsl 
     xtempright += 1 
     result += q2 
    print(result) 

打印我需要在同一行我得到它像Q2的空間消失在某處,並沒有連接。

/\ 
/\ 
/\ 
/ \ 
/ \ 

任何人都可以幫助我嗎?我嘗試了很多方法,但無法得到它。

+0

您的預期輸出是多少? – Sajin

回答

0

隨着/推移留在每行一個位置,你需要的\前一個附加空間。在Q2中寫入就足夠了:

q2 = space * 2 * xtempright + bsl 
+0

謝謝!這正是我所期待的。 – Emejcz

1

在修改中,您省略了for循環。

在您的初始代碼中有兩個for循環,在您的修改中,您省略了第二個for循環。

+0

爲什麼你不想要一個for循環?在第一種情況下有2 * n行,第二種情況下只有n行 – Sajin

0

如果這是你期望的輸出,

/\ 
/\ 
/ \ 
/ \ 
/  \ 

修改#Q2到:

if xtempright == 0: 
     xtempright += 1 
     q2= bsl 
     result += q2 
    else: 
     q2 = space * (xtempright+1) + bsl 
     xtempright += 2 
     result += q2