[英]why is python generating a half space when printing from a string or list?
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!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.