Python 3.x Python:检查字符串中的字符
因此,我一直在努力使这项工作,但我不知道哪里是错的。文本文件包含:Python 3.x Python:检查字符串中的字符,python-3.x,Python 3.x,因此,我一直在努力使这项工作,但我不知道哪里是错的。文本文件包含: III @@@ 这就是我目前所拥有的。我看不出有什么不对 CHARACTERS = ["I","@"] def checkFile(): inFile = open("random.txt","r") text = inFile.read() inFile.close() x = True for line in text: line.strip() for
III
@@@
这就是我目前所拥有的。我看不出有什么不对
CHARACTERS = ["I","@"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
它应该打印“bye”,因为文件中的所有字符都在列表中;但是,它只是在没有print语句的情况下退出。当一个
txt
文件包含两行文本,一行在另一行之上时,它还包含一个隐藏的'\n'
。若要更改,请将'\n'
添加到字符,或复制以下代码:
CHARACTERS = ["I","@", "\n"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
>>> file = open('test.txt', 'r').read()
>>> file
'III\n\n@@@\n'
>>>
编辑:我创建了一个名为test.txt的txt
文件,并将您的文本粘贴到其中。然后我运行了以下代码:
CHARACTERS = ["I","@", "\n"]
def checkFile():
inFile = open("random.txt","r")
text = inFile.read()
inFile.close()
x = True
for line in text:
line.strip()
for i in range(len(line)):
if line[i] in CHARACTERS:
x = True
else:
x = False
return False
return True
def main():
check = checkFile()
if check == False:
sys.exit()
elif check == True:
print("bye")
sys.exit()
main()
>>> file = open('test.txt', 'r').read()
>>> file
'III\n\n@@@\n'
>>>
因为中间有两行,所以它有teo'\n'
s。您可以通过将'\n'
添加到字符,或使用split()
调用text=infle.read().split()
来消除此问题
调用line.strip()
时,没有将line.strip()
赋值给任何值。因此,可以说,'\n'
仍然是“未压缩的”。相反,请调用line=line.strip()
我不想要换行符,这就是为什么我使用line.strip来删除新行,所以它不应该有任何区别。实际上,文本文件包含“III\n@@@n”,即使在我执行拆分函数并修复line.strip()时,它也不能正常工作。为什么当它正在剥离的行,然后要求检查该行中的字符时\n它不工作。strip应该删除\n但不是当我运行代码修复line=line.strip()
时,输出是bye
。请尝试再次检查代码。是否也在使用其他修复程序?