TShopping

標題: Python 字串前 加 u、r、b 的意思 [打印本頁]

作者: woff    時間: 2022-5-24 22:51
標題: Python 字串前 加 u、r、b 的意思
Python 3 中的編碼預設就是unicode,不過在字串前加上u,依舊可以強迫轉換後續字串為unicode:

#將字串編碼成 unicode
  1. str1 = u"今天天氣很好"
  2. print(str1)
複製代碼
結果:

今天天氣很好


字串前面加上r代表不將特殊字元編譯:

  1. #將字串中的特殊符號不進行編譯
  2. str2 = r"我\n想吃水果"
  3. str3 = "我\n想吃水果"
  4. print(str2)
  5. print(str3)
複製代碼

結果:

我\n想吃水果

想吃水果

很清楚地發現str3中的\n有被編譯成”換行”

最後一個b代表bytes,python 2中的字串預設編碼是 bytes,它只能對應到python 3 中 ASCII 中的編碼,如果字串是中
文字就會報錯:

參考文章
https://xken831.pixnet.net/blog/ ... 4%E6%84%8F%E7%BE%A9





歡迎光臨 TShopping (http://www.tshopping.com.tw/) Powered by Discuz! X3.2