【问题标题】:I can't convert a unicode into a plain string我无法将 unicode 转换为纯字符串
【发布时间】:2019-10-28 22:01:18
【问题描述】:

我很难将一个单词从 unicode 转换为纯字符串。我在寻找答案,但没有人帮我解决这个简单的问题。

我已经尝试过以下链接: https://www.oreilly.com/library/view/python-cookbook/0596001673/ch03s18.html

Convert a Unicode string to a string in Python (containing extra symbols)

How to convert unicode string into normal text in python

from bs4 import BeautifulSoup

r = requests.get('https://www.mpgo.mp.br/coliseu/concursos/inscricoes_abertas')
soup = BeautifulSoup(r.content, 'html.parser')

table = soup.find('table', attrs={'class':'grid'})

text = table.get_text()
text_str = text[0:7]
text_str = text_str.encode('utf-8')

test_str = 'Nenhum'
test_str = test_str.encode('utf-8')

if text_str == test_str:
    print('Ok they are equal')
else:
    print(id(text_str))
    print(id(test_str))
    print(type(test_str))
    print(type(test_str))
    print(test_str)
    print(test_str)```

My spected result is: text_str being equal test_str

【问题讨论】:

    标签: python-3.x beautifulsoup


    【解决方案1】:

    欢迎来到 SO。您的调试输出中有错字。最后 4 个值都是 test_str,而不是一些 text_str。

    然后你会注意到你读入的变量包含:

    '\nNenhum'
    

    因此,如果您将切片更改为: text_str = text[1:7] 或相应地设置测试字符串:

    test_str = '\nNenhum'
    

    它有效。快乐的黑客...

    【讨论】:

    • 嘿伙计,你刚刚救了我的命。下次我会更加注意我的代码输入。
    猜你喜欢
    • 2012-07-19
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    相关资源
    最近更新 更多