V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
pppguest3962
V2EX  ›  Python

python3,判断字符串是否相等,学习过程中,我用了四种做法都错,求指点。。。

  •  
  •   pppguest3962 · 2018-08-19 15:47:21 +08:00 · 5012 次点击
    这是一个创建于 2049 天前的主题,其中的信息可能已经有所发展或是发生改变。
    htmlfile = open('D:/test.htm','rb')
    htmlhandle = htmlfile.read()
    soup = BeautifulSoup(htmlhandle, 'lxml')
    table = soup.select('tr > td')
    
    for tr in table:
        infostr = re.findall('stream="adfs-(\d+)',tr.prettify())
        #做法 1
        if (infostr.__str__() in "1776"):
            print(infostr.__str__())
            
        #做法 2
        import operator       
        if (operator.eq(infostr.__str__(),"1776"))
            print(infostr.__str__())
        
        #做法 3,这个应该是 python2 的时候能用起来,python3 应该不行了吧?
        if (infostr.__str__() == "1776")
            print(infostr.__str__())
        
        #做法 4,把 1776 强制指定为字符串变量,结果还是不行
        import operator       
        if (operator.eq(infostr.__str__(),"1776"))
            print(infostr.__str__())
    

    想通过正则,判断截取出来的字符,是不是文本 1776 这个字符串?

    已试过:

    for tr in table:
       print tr
    

    确定 tr 是已经获取到字符串的了。。。。

    求问正确的做法应该是?

    5 条回复    2018-08-19 22:37:41 +08:00
    kba977
        1
    kba977  
       2018-08-19 15:50:44 +08:00
    infostr 是一个列表呀
    ranleng
        2
    ranleng  
       2018-08-19 15:58:28 +08:00
    如 #1 说的.
    re.findall 返回的是一个 list
    pppguest3962
        3
    pppguest3962  
    OP
       2018-08-19 15:58:44 +08:00
    @kba977,我真是傻了。。。意识到自己的错误,不胜感谢!!!
    wwqgtxx
        4
    wwqgtxx  
       2018-08-19 21:01:29 +08:00 via iPhone
    而且为啥要手动调用.__str__不应该用 str()的么
    talen666
        5
    talen666  
       2018-08-19 22:37:41 +08:00
    if infostr[0].find('1776) != -1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2651 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 15:18 · PVG 23:18 · LAX 08:18 · JFK 11:18
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.