使用 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
由于 /
每行左移一位,因此您需要在 \
之前添加一个 space。 Q2写就够了:
q2 = space * 2 * xtempright + bsl
当我 运行 此代码时,它的行为符合预期:
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
由于 /
每行左移一位,因此您需要在 \
之前添加一个 space。 Q2写就够了:
q2 = space * 2 * xtempright + bsl