gpt4 book ai didi

python - 为什么Python在从字符串或列表打印时生成半个空格?

转载 作者:行者123 更新时间:2023-12-01 05:41:39 26 4
gpt4 key购买 nike

finale_line=[]
print type(finale_line)#just checking#
lot_number=()
number_drawn=()
def load():
first=input("enter first lot: ")
last=input("enter last lot: ")
for lot_number in range(first,last):
line_out=str(lot_number)
for count in range(1,5):
number_drawn=raw_input("number: ")
line_out=line_out+number_drawn
print line_out #making sure it's a string at this point#
finale_line.append(line_out)
finale_line2=finale_line

load()


print finale_line #again just checking#
print(" "*4),
for n in range(1,21):
print n, #this is to produce a line of numbers to compare to output#
for a in finale_line:
print"\n",
print a[0]," ",
space_count=1
for b in range(1,5):
if int(a[b])<10:
print(" "*(int(a[b])-space_count)),int(a[b]),
space_count=int(a[b])
else:
print(" "*(a[b]-space_count)),a[b],
space_count=a[b]+1

我很抱歉没有真正说出“?”这会让我在危险边缘付出代价。 2:我发布了两次,因为我认为第一个搞砸了。3:发布的代码是一个旧的已失效版本,但令我担心的是你得到的错误消息与我不同。我不确定这个版本会在您的计算机上产生相同的结果。这一直是 python 的一个持续存在的问题。

>>>
<type 'list'>
enter first lot: 1
enter last lot: 4
number: 2
number: 3
number: 4
number: 5
12345
number: 1
number: 2
number: 3
number: 4
21234
number: 3
number: 4
number: 5
number: 6
33456
['12345', '21234', '33456']
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
1 2 3 4 5
2 1 2 3 4
3 3 4 5 6
>>>

我意识到我的逻辑在间距方面存在问题,但我认为这可以解决。我不明白的是半个空格是从哪里来的。或者也许需要一种完全不同的方法。感谢您的回复,我不想浪费任何人的时间,但非常感谢

最佳答案

我不知道你所说的“一半”空格是什么意思,但我认为让你感到困惑的是你认为不应该出现在数字之间的“额外”空格;我说得对吗?

如果是这样,那么它来自 print 语句中的最后一个逗号。您正在使用它来阻止 print 在输出后打印换行符 - 但您没有意识到,当它遇到该逗号时,它会打印一个额外的空格。在 Python 命令提示符下尝试一下:

>>> def hello():
... print "Hello",
... print "world"
...
>>> hello()
Hello world

我在“Hello”后面没有加空格,那么它是从哪里来的呢?答案:逗号。

您的困惑主要源于两件事:1)使用了错误的工具来完成工作,2)缺乏对 Python 如何输出的深入理解(Python 初学者可以理解)。

问题 1 可以通过使用 sys.stdout.write() 而不是 print 来解决。 (请注意,您需要import sys才能使用它)。 write() 不会添加任何空格或换行符;您需要自己指定空格和换行符。 (Python 字符串中的换行符是 \n,以防您忘记)。因此您的输出将更加可预测。

问题 2 可以通过 http://docs.python.org/2/tutorial/inputoutput.html 解决尽快地。请注意 .rjust().format() 等字符串方法的使用:习惯这些方法,您就会爱上它们。事实上,您很快就会想知道为什么您会想要再手动进行这种字符串格式化,因为有如此强大的函数可以为您做到这一点。

希望这对您有所帮助,并祝您学习 Python 愉快!

关于python - 为什么Python在从字符串或列表打印时生成半个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17386936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com