从函数中的类型错误开始 [英] startswith TypeError in function

查看:46
本文介绍了从函数中的类型错误开始的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

    def readFasta(filename):
        """ Reads a sequence in Fasta format """
        fp = open(filename, 'rb')
        header = ""
        seq = ""
        while True:
            line = fp.readline()
            if (line == ""):
                break
            if (line.startswith('>')):
                header = line[1:].strip()
            else:
                seq = fp.read().replace('\n','')
                seq = seq.replace('\r','')          # for windows
                break
        fp.close()
        return (header, seq)

    FASTAsequence = readFasta("MusChr01.fa")

我得到的错误是:

TypeError: startswith first arg must be bytes or a tuple of bytes, not str

但是根据文档,startswith 的第一个参数应该是一个字符串......那么这是怎么回事?

But the first argument to startswith is supposed to be a string according to the docs... so what is going on?

我假设我至少使用 Python 3,因为我使用的是最新版本的 LiClipse.

I'm assuming I'm using at least Python 3 since I'm using the latest version of LiClipse.

推荐答案

这是因为您以字节模式打开文件,因此您调用的是 bytes.startswith() 而不是 <代码>str.startswith().

It's because you're opening the file in bytes mode, and so you're calling bytes.startswith() and not str.startswith().

你需要做line.startswith(b'>'),这将使'>'成为字节字面量.

You need to do line.startswith(b'>'), which will make '>' a bytes literal.

这篇关于从函数中的类型错误开始的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆