字串是 Python 裡最常打交道的型別,而輸入輸出是它最基礎的兩件事。以下以 Python 2 的行為為主整理,並標出 Python 3 的差異,避免踩到版本地雷。
Python 2 有兩個內建函式:raw_input() 一律回傳字串;input() 相當於 eval(raw_input(prompt)),會先對輸入內容求值,因此輸入非運算式時容易出錯。
help(input)
# input([prompt]) -> value
# Equivalent to eval(raw_input(prompt)).
input() # 輸入 d -> NameError: name 'd' is not defined
input() # 輸入 23 -> 23
input("input a num") # 輸入 444 -> 444
n = input() # 輸入 23 -> n 為整數 23
s = raw_input("input sth.: ") # 輸入 123 -> s 為字串 '123'
s = raw_input("input sth.: ") # 輸入 sss -> s 為字串 'sss'
Python 3 的差異:取消了 raw_input(),input() 的行為改為「一律回傳字串」,不再做 eval。要轉型別請自行 int()、float()。這項變動讓輸入行為更可預測,也少了很多安全性疑慮。
Python 2 用 print 陳述式,Python 3 改為 print() 函式。引號可用單引號、雙引號或三重引號包覆,並可互相嵌套(同種引號需轉義)。
print "i'm Tom" # i'm Tom print 'abc' # abc print "abc" # abc print '''abc''' # abc print '"hhh"' # "hhh" print "'hello world'" # 'hello world' print 'i\'m bt' # i'm bt(轉義) print '''i'm tom, "hhhe"''' # 可同時包含兩種引號
print '''i am tom hhha''' # 三重引號保留換行 print 'i am \ tom \ hh' # 反斜線續行,輸出為同一行 print " i\ am \ tom \ " # 搭配 \n 亦可控制換行與空行
print r"I\'m Tom" # 原始字串,反斜線不生效:I\'m Tom
需要輸出路徑、正則表達式時,r"" 原始字串能省下大量反斜線,值得養成習慣。
n = raw_input() # 輸入 123,得到字串 '123' n = int(n) # 轉為整數 123 str(n) # 再轉回字串 '123'
其他常用轉換:float() 轉浮點、str() 轉字串;Python 2 若要處理大量非 ASCII 文字,還會用到 unicode() 與 encode()/decode(),Python 3 則統一為 str 與 bytes 兩種型別,編碼問題單純許多。
除了字串串接,更推薦格式化寫法,效能與可讀性都更好:
name = "Tom"
age = 18
print("%s is %d years old" % (name, age)) # 舊式
print("{} is {} years old".format(name, age)) // 新式
print(f"{name} is {age} years old") // Python 3.6+ 最簡潔
迴圈中大量輸出時,避免用 + 反覆串接字串,改用格式化或 ''.join(...),這是 Python 效能上最基本的常識。