繁体   English   中英

使用Python将字符串与空格连接

[英]Concatenating strings with spaces using 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的空格消失在某处并没有连接。

    /\
   / \
  /  \
 /   \
/    \

有人可以帮我这个吗? 我在很多方面都尝试过但无法得到它。

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

在您的初始代码中有两个for循环,在您的修改中,您省略了第二个for循环。

如果这是您的预期输出,

    /\
   /  \
  /    \
 /      \
/        \

将#Q2修改为:

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

/在每一行上留下一个位置时,在\\之前需要一个额外的空格。 在第二季度写作就足够了:

    q2 = space * 2 * xtempright + bsl

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM