Python3字节与字符串不同,startswith识别字符串方法,及pythonchallenge第四关代码

在解决PythonChallenge第四关时,遇到`startswith`方法报错,原因是`urlopen().read()`返回的是bytes类型,而非str。通过查阅资料,了解到Python3中字节和字符串是不同的。为了解决这个问题,需要将bytes转换为str,通过`.decode`方法实现。最终修正后的代码能正常运行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最早在做Pythonchallenge时我参考了下文的代码
https://blog.youkuaiyun.com/zrzlj/article/details/48805433
但这篇文章并不是基于Python2,有一些语法不适用

其中会发生报错

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

应该是说startswith只能识别bytes,不能识别str

这似乎是因为urlopen().read(),返回的是bytes类型

根据这篇文章
https://www.jianshu.com/p/efcff000b81a
Python3应该是区分了字节与字符串

所以我对代码进行了修改,下面是可以正常运行的代码

import urllib
 
def main():
    resp = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=63579").read()
    t = 0
    while True:
        print (t)
        t = t+1
        print (resp)
        if t >= 400:
            break
        if resp.startswith(b"<font color=red>Your hands are getting tired </font>and the next nothing is "):
            resp = resp.replace(b"<font color=red>Your hands are getting tired </font>and the next nothing is ",b"")
            print(resp.decode())
            resp = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="+resp.decode()).read()
            print(resp)
        elif resp.startswith(b"and the next nothing is "):
            resp = resp.replace(b"and the next nothing is ", b"")
            resp = urllib.request.urlopen("http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing="+resp.decode()).read()
        else:
            print (resp)
            break
 
 
 
if __name__ == '__main__':
    main()

这里对网页内容读取、判断、修改的resp变量一直为bytes型,之后因为要加入url需要转换为str型,所以参考这篇文章
https://www.cnblogs.com/niuu/p/10106897.html
我使用resp.decode进行转换

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值