python - 函数不适用于文件中的空格

标签 python python-3.x

def square(sq):
    grid = len(sq)
    for line in sq:
        if len(line) != grid:
            raise ValueError


while True:
try: 
    filesname = input("Enter the filename:") + ".txt"
    file = open(filesname,"r")
    readFile = file.readlines()
    file.close()
    thelist = [line.strip() for line in readFile]
    square(thelist)
    print ("File has:")
    print("\n".join(thelist))


except FileNotFoundError: 
    print ("The file name you have entered does not exist. Please try again.")
except ValueError:
    print ("")
    print ("Incorrect file format")
else:
    break

我尝试打开的文件是:

A B C
B C A
C A B

我想打开文件并检查它是否是方形网格,然后向用户报告是否是。正如您所看到的,上面的文件是一个方形网格,但我的程序说它不是。

当我执行此代码时,它一直显示“文件格式不正确”。我认为这与平方函数有关,并且它没有考虑字母之间的空格,我不知道如何解决这个问题,有人可以帮助我吗?

最佳答案

您遇到了声音相似的问题:

>>> "A B C\n".split()
['A', 'B', 'C']
>>> "A B C\n".strip()
'A B C'

换句话说,使用split(),而不是strip()

关于python - 函数不适用于文件中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35915302/

相关文章:

python - matplotlib.pyplot.hist 错误的规范属性

python - 如何避免 if/else 语句中的重复代码?

python - 如何在 Rasa 中获取最后的用户输入

python - 使用 cx_Freeze 时出现属性错误

python - 有没有一个Python函数可以丢弃或忽略负值?

python - 您可以更改 Django Admin 应用程序中的字段标签吗?

python - 如何使用 django.views.generic.date_based.archive_index 获取前五个对象?

python - 运行游戏时出现空白窗口

python - dict python的URL查询参数

python - 使用推导式将 Python 字典数组转换为 Python 字典