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

看板Python作者 (花生)時間10年前 (2013/11/21 00:02), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串4/5 (看更多)
有解了!!! 自己來回自己的文 Python 2跟Python 3對字串的處理函式不太一樣 在Python 3中,不用在程式裡特別打上『# -*- coding: utf8 -*-』 他預設裡面所有的字元都是utf-8編碼了。 s = "中文" #這個"中文"是utf-8編碼,變數s的型態是string utf8ByteString = s.encode("utf-8") utf8ByteString 為『以utf-8編碼的byte string, 型態是byte喔』 而 big5ByteString = s.encode("big5") big5ByteString 為『以big5編碼的byte string, 型態是byte喔』 型態是byte的變數,他的encode, decode方法跟一般string又不太一樣(雖然名字一樣) byte變數的decode(),是將原本的byte以指定的編碼方式轉回來。 ex: result1 = utf8ByteString.decode("utf-8") result1內容為"中文" result2 = big5ByteString.decode("big5") result2內容為"中文" 謝謝每個回應的板友! 你們的回應才讓我有動力繼續研究T_T ※ 引述《icycandle (你有壓力,我有壓力)》之銘言: : 我習慣的工作環境是 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: 114.24.63.240 ※ 編輯: peanut97 來自: 114.24.63.240 (11/21 00:09)
文章代碼(AID): #1IZDqZ4- (Python)
討論串 (同標題文章)
文章代碼(AID): #1IZDqZ4- (Python)