python如何输出文字和变量,如何在Python中转换带有特殊字符的字符串变量以正确打印...

Sorry if the title is confusing but I have literally researched this for two hours and have no idea how I am supposed to ask this question so anyone feel free to edit this post.

I have this string variable that I created using web scraping and it uses special characters and looks something like "\ud83d\ude00\u0107\u00e7 \n hello" without the quotations when I print it. The issue is that I want it to print the actual special characters but I am not sure what encoding method I should use. If I copy and paste the exact string and print it, it works fine but as a variable I created, it doesn't display the special characters, just the text.

I have tried converting it to a string, using json.load, unicode-escape, UTF-8, and a bunch of others but I am honestly not sure what method I should use

page = requests.get('https://www.example.com')

soup = str(BeautifulSoup(page.text, 'html.parser')).splitlines()

for line in soup:

if 'hello' in line:

print(line) #produces literal text of \ud83d\ude00\u0107\u00e7 \n hello

print('\ud83d\ude00\u0107\u00e7 \n hello') #produces wanted result

I would like to outcome to look like this:

😀ćç

hello

解决方案

Through another hour of trial and error, I figured out this was the answer:

line.encode('utf-8').decode('unicode-escape')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值