Concatenate strings with spaces using Python

When I run this code, it behaves as expected:

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)

      

I get this:

    /
   /
  /
 /
/
\
 \
  \
   \
    \

      

The problem is when I try to make some changes:

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)

      

to print what I need on the same line, I get it as spaces from Q2, missing somewhere and no concatenation.

    /\
   / \
  /  \
 /   \
/    \

      

Can anyone help me? I've tried in different ways and can't get it.

+3


source to share


3 answers


As it /

moves one position to the left of each line, you need one more space before \

. It is enough to write in Q2:



    q2 = space * 2 * xtempright + bsl

      

0


source


In the modification, you omitted the for loop.



There are two loops in your original code and in your modification you missed the second loop of the loop.

+1


source


If this is your expected output,

    /\
   /  \
  /    \
 /      \
/        \

      

Change # Q2 to:

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

      

0


source







All Articles