1. 程式人生 > >python 自學筆記(1)字串(python程式設計從入門到實踐)

python 自學筆記(1)字串(python程式設計從入門到實踐)

使用方法改寫字串大小寫

name=”Ada lovelace”
print(name.upper())
print(name.lower())

結果:

ADA LOVELACE
ada lovelace

合併(拼接)字串

方法1:直接通過加號(+)操作符連線

first_name=”ada”
last_name=”lovelace”
full_name=first_name+” “+last_name

結果

ada lovelace
效率較低,會為產生的新字串重新申請記憶體空間

刪除空白

favorite_language=’python ’
favorite_language

輸出

‘python ‘

刪除最後空格可用rstrip()

favorite_language.rstrip()

輸出

‘python’

刪除最前邊的空白

favorite_language=’ python ’
favorite_language.lstrip()

輸出

‘python ‘

刪除前後空白

favorite_language=’ python ’
favorite_language.strip()

結果

‘python’

使用函式str()避免型別錯誤

age=23
message=”happy”+age+”birthday”
print(message)

出現型別錯誤,python不知道怎麼對資料進行解析,因為23 python可理解為數字23或者是字元2和3

File “E:/PycharmCode/demo1.py”, line 19, in
message=”happy”+age+”birthday”
TypeError: can only concatenate str (not “int”) to str

修改

age=23
message=”happy”+str(age)+”birthday”
print(message)

結果

happy23birthday