Re: 新手想寫登入BBS的程式(Python 3)

看板Python作者 (你有壓力,我有壓力)時間12年前 (2013/11/19 19:42), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/5 (看更多)
我習慣的工作環境是 python2.7 @ Unix-like OS,不過就來拋磚引玉一下。 首行的「# -*- coding: big5 -*-」是用來跟 interpreter 溝通用的, 換言之,只是讓interpreter可以看懂你的source code。這跟程式的行為 (字串到底是用何種編碼)應該沒有關係。 既然是 python3 預設的字串應該一律是 unicode。 如果要輸出 Big5 的話,應該可以試試: "請輸入代號".encode('cp950') cp950 基本上就是微軟的Big5編碼實作。 ※ 引述《peanut97 (花生)》之銘言: : 我又做了新的測試: : 程式碼: : =============================================== : # -*- coding: big5 -*- : import telnetlib : tn = telnetlib.Telnet('ptt.cc') : s = tn.read_until(b"ptt3") : print(s) : =============================================== : 會印出ptt的首頁畫面 : 但改成read_until(b"請輸入代號"),就不行,程式碼: : =============================================== : # -*- coding: big5 -*- : import telnetlib : tn = telnetlib.Telnet('ptt.cc') : s = tn.read_until(b"請輸入代號") : print(s) : =============================================== : 會顯示錯誤:『bytes can only contain ASCII literal characters.』 : 看read_until的文件,他接受的參數是byte string,所以應把字串轉成byte string : 但看程式碼第一行是用big5 : 是不是指字串:『請輸入代號』已經是big5編碼 : 所以要想辦法把big5 轉成byte string ? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.171.174.223 ※ 編輯: icycandle 來自: 1.171.174.223 (11/19 19:43)
文章代碼(AID): #1IYqwase (Python)
文章代碼(AID): #1IYqwase (Python)