字串

Python 的資料型別

Jason Myers

Instructor

建立格式化字串

  • f-strings(格式化字串常值)- f""
cookie_name = "Anzac"
cookie_price = "$1.99"

print(f"Each { cookie_name } cookie costs { cookie_price }.")
"Each Anzac cookie costs $1.99."
Python 的資料型別

用字串來串接

  • "".join() 會用被呼叫的字串來串接可疊代物件
child_ages = ["3", "4", "7", "8"]

print(", ".join(child_ages))
"3, 4, 7, 8"
print(f"The children are ages {','.join(child_ages[0:3])}, and {child_ages[-1]}.")
"The children are ages 3, 4, 7, and 8."
Python 的資料型別

比對字串片段

  • .startswith().endswith() 可判斷字串是否以某字元或字串開頭或結尾
boy_names = ["Mohamed", "Youssef", "Ahmed"]
print([name for name in boy_names if name.startswith('A')])
["Ahmed"]
  • 注意:這些方法與多數字串函式都區分大小寫。
Python 的資料型別

在字串中搜尋

  • in 運算子會在可疊代型別(如字串)中搜尋某個值。
"long" in "Life is a long lesson in humility."
True
"life" in "Life is a long lesson in humility."
False
Python 的資料型別

不區分大小寫的作法

  • .lower() 會回傳全小寫字串
"life" in "Life is a long lesson in humility.".lower()
True
Python 的資料型別

一起來練習吧!

Python 的資料型別

Preparing Video For Download...