python中print函数的输出问题(空格,制表符)

python中print函数的输出问题(空格,制表符)

前言

在做编程题目时,为什么程序的实际输出和预期输出“看上去明明一模一样”,但是就是提示有误呢???

在此记录。

问题描述

最近在看educoder实训平台上的一道编程题,题目要求大概是:

educoder中判断程序是否正确,是通过输出结果的字符串匹配来判断的。

然而涉及到这个制表符,空格的输出问题时,很容易出错。

比如:

我的程序一开始是这样:

def day(y, m, d):#计算y年m月d日是星期几

# 请在下面编写代码

y0=y-(14-m)//12

x=y0+y0//4-y0//100+y0//400

m0=m+12*((14-m)//12)-2

d0=(d+x+(31*m0)//12)%7

# 请不要修改下面的代码

return d0

def isLeapYear(year): #判断year年是否闰年

# 请在下面编写代码

a=year%4

b=year%100

if(a==0 and b!=0):

isLeapYear="True"

else:

isLeapYear="False"

# 请不要修改下面的代码

return isLeapYear

def calendar(y, m): #打印y年m月日历

print(' {}年{}月'.format(y,m))

print('Su\tM\tTu\tW\tTh\tF\tSa')

# 请在下面编写代码

if(isLeapYear(y) is "True"):

list_1=[31,29,31,30,31,30,31,31,30,31,30,31]

firstday=day(y,m,1)

count=0

while(count

print("\t",end="")

count+=1

a=1

while(a<=list_1[m-1]):

print(a,'\t',end="")

a+=1

count+=1

if(count%7==0):

print("")

if(a>list_1[m-1]):

print("")

else:

list_2=[31,28,31,30,31,30,31,31,30,31,30,31]

firstday=day(y,m,1)

count=0

while(count

print("\t",end="")

count+=1

a=1

while(a<=list_2[m-1]):

print(a,'\t',end="")

a+=1

count+=1

if(count%7==0):

print("")

if(a>list_2[m-1]):

print("")

测评结果是这样的:

实在让人崩溃,明明是一模一样的,为什么会错呢???

解决方法

1 发现问题

我截取了预期输出和实际输出中的一行,进行比较:

import difflib

s1='''

1 2 3 4 5

'''

s2='''

1 2 3 4 5

'''

print('s1 is equal to s2 ? The answer is ',s1==s2)

发现输出为:

果然不一样。

2 解决问题

通过这个,我终于发现:

原来s2(也就是我的实际输出)对比s1,是多了一个空格的。

太神奇了,原来空格+制表符 看上去还是和 制表符 一样!!!

错误代码在:

print(a,'\t',end="")

修改成:

print('%d\t'%a,end="")

这样就对了。!!!

为什么:

因为print(a,'\t',end="") 中 a和'\t'中间隔了一个逗号,导致二者之间多输出了一个空格。

比如:

输入代码

a=1

b=2

print(a,b)

输出不是12,而是1 2。

中间是有空格的(原因就在于a和b之间的逗号)

3 程序通过

总结

当教辅实在太花时间了。

相关文章