Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么我在输出正确字符串的同时输出错误字符串_Python_String - Fatal编程技术网

Python 为什么我在输出正确字符串的同时输出错误字符串

Python 为什么我在输出正确字符串的同时输出错误字符串,python,string,Python,String,我正在上python的初学者编程课,我们刚刚开始学习字符串。我们的第一个任务是访问文本文件并返回包含指定字母的行。然而,当我这样做时,我得到一行是正确的,另一行是完全错误的 text = open('some.txt') def countLine(text): q = 0 for c in text: return(c) def countLetterFile(char): for f in countLine(text): if f == char:

我正在上python的初学者编程课,我们刚刚开始学习字符串。我们的第一个任务是访问文本文件并返回包含指定字母的行。然而,当我这样做时,我得到一行是正确的,另一行是完全错误的

text = open('some.txt')
def countLine(text):
q = 0 
for c in text:
    return(c)

def countLetterFile(char):
    for f in countLine(text):
        if f == char:
            print(countLine(text))
        else:
            pass
countLetterFile('w')
它应该打印“单词组成其他单词” “言成句” 还有“我有微软word”

相反,我得到了这个

This is a line

words make sentences

一旦函数使用return语句返回某个内容,它就会中断

为什么不检查一下信是否在队列中

def countLetterFile(char):
    for f in text:
        if char in f:
            print(f)

下面是代码的问题。在countLine函数中,您将浏览该行的字符。您正在使用此功能进行检查,然后再次使用此功能进行打印。您只需要打印文本而不是countLinetext

或者,您可以执行以下操作:

if char in text:
    print(text)

检查您的缩进解决了我的问题,但为什么它返回了错误的字符串?@user2330498我想这是因为您在打印时调用了countLinetext。所以它打印下一行而不是当前行