简体   繁体   English

.readline()在Python中返回什么?

[英]What does .readline() return in Python?

EDIT of entire post, in order to be more clear of the problem: 编辑整个帖子,以便更清楚地解决问题:

s = "GATATATGCATATACTT"
t = "ATAT"

for i in range(len(s)):
    if t == s[i:i+len(t)]:
        print i+1,

So the purpose of the program above is to scan through the long line of DNA (s) with the short line of DNA (t), in order to find at which positions on s, that t matches. 因此,上面程序的目的是扫描DNA的长线和DNA的短线(t),以找出t在s上的哪个位置匹配。 The output of the above code is: 上面代码的输出是:

2 4 10 #This are basically the index numbers of string s that string t matches. 2 4 10#这基本上是与字符串t匹配的字符串s的索引号。 but as can be seen in the code above, it's i+1 to give a 1-based numbering output. 但从上面的代码中可以看出,i + 1给出基于1的编号输出。

The problem I'm having is that when i try to change the code, in order to make it receive the values for s and t through a file, the readline() function is not working for me. 我遇到的问题是,当我尝试更改代码时,为了使其通过文件接收s和t的值,readline()函数对我不起作用。 The motif.txt file contains two strings of DNA, one on each line. motif.txt文件包含两串DNA,每行一行。

with open('txt/motif.txt', 'r') as f:

    s = f.readline()
    t = f.readline()

    for i in range(len(s)):
        if t == s[i:i+len(t)]:
            print i+1,

So this code, on the other hand will output nothing at all. 因此,另一方面,此代码将什么也不输出。 But when I change t to: 但是当我将t更改为:

t = f.readline().strip()

Then the program outputs the same result as the first example did. 然后程序输出与第一个示例相同的结果。

So i hope this has made things more clear. 所以我希望这可以使事情变得更清楚。 My question is thus, if readline() returns a string, why isn't my program in example 2 working in the same way as in the very first example? 因此,我的问题是,如果readline()返回一个字符串,为什么示例2中的程序不能以与第一个示例相同的方式工作?

your problem statement is wrong, there's no way s or t has more content (and len(s) > 0 or len(t) > 0 ) in the first example than in the second. 您的问题陈述是错误的,第一个示例中的st不可能拥有比第二个示例更多的内容(并且len(s) > 0len(t) > 0 )。

basically with: 基本上有:

s = f.readline()

then s will contain a string like "foobar \\n" , and thus len(s) will be 9 . s将包含诸如"foobar \\n"类的字符串,因此len(s)将为9

Then with: 然后加上:

s = f.readline().strip()

with the same string, len(s) will be 6 because the stripped string is "foobar" . 使用相同的字符串,则len(s)将为6因为剥离的字符串是"foobar"

so if you line is full of spaces like s = " \\n" , s.strip() will be the empty string "" , with len(s) == 0 . 因此,如果行中充满s = " \\n"s = " \\n"空格,则s.strip()将为空字符串"" ,其中len(s) == 0

Then in that case your loop won't start and will never print anything. 那样的话,您的循环就不会启动,也不会打印任何内容。

in almost all the other cases I can think of, you should get an execption raised, not silent exit. 在我能想到的几乎所有其他情况下,应该提高执行力,而不是无声退出。

But to be honest, your code is bad because nobody can understand what you want to do from reading it (including you in six months). 但老实说,您的代码很糟糕,因为没有人能读懂您想做什么(包括六个月内的您)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM