# 文字字串 ### Story about string --- <!-- .slide: data-background="https://hackmd.io/_uploads/ByB5Vi_bC.jpg" --> ## About Me - Yoyo - Volunteer of PyCon TW since 2022 - 雙棲 Backend + AI 工程師 ![IMG_1554](https://hackmd.io/_uploads/SJR9tOPZC.jpg =30%x) --- ## 字串 ```python ss = "這是一個字串" aa = '這也是一個字串' print(ss) # 這是一個字串 print("這串字總共有" + str(len(ss)) + "個字") # 字串加法 five = 5 print(str(five) * five) # 字串乘法,輸出:55555 # 多行字 s_long = """ 這串字有好多行 This string contains multiple lines. """ print(s_long) ``` ---- ## 特殊字元 ```python newline = "\n" tab = "\t" raw_str = r"這裡面\n不會被換行" extra_quote = "這裡面多了一個\"雙引號" ``` --- ## String <=> Byte 轉換 ```python s1 = "I am byte man" s2 = b"I am byte man" print(type(s1), type(s2)) # str, bytes print(s1 == s2) # False print(s1.encode("UTF8") == s2) # True print(s1 == s2.decode("UTF8")) # True ``` --- ## 基本操作 ---- ### `split` ```python ss = "你我,相隔兩地 卻又彼此糾纏" # 依照空格分開 print(ss.split()) # 你我,相隔兩地 / 卻又彼此糾纏 # 依照指定字元分開 print(ss.split(",")) # 你我 / 相隔兩地 卻又彼此糾纏 ``` ### `strip` <font size=5> 移除前方與後方的空格、特殊字元 </font> ```python ss = " 清空前方與後方障礙 中間不受影響 \n" print(ss.strip()) # "清空前方與後方障礙 中間不受影響" ``` ---- ### `replace`, `index` ```python ss = "Hello, I am Yoyo" print(ss.replace("Yoyo", "Gobby")) # Hello, I am Gobby print(ss.index("Yoyo")) # 12 ``` ---- ### `startswith`, `endswith` ```python ss = "Today is so HOT" print(ss.startswith("Tod")) # True print(ss.endswith("OT")) # True ``` ---- ### 變換大小寫 ```python ss = "Hello there. Nice to meet you~" print(ss.lower()) # hello there. nice to meet you~ print(ss.upper()) # HELLO THERE. NICE TO MEET YOU~ print(ss.title()) # Hello There. Nice To Meet You~ print(ss.swapcase()) # hELLO THERE. nICE TO MEET YOU~ ``` ---- ### `join` ```python ss = "啊啊啊,是逗號" s_list = ss.split(",") print("-".join(s_list)) # 啊啊啊-是逗號 ``` ---- ### in 判斷 ```python ss = "People mountain people sea" print("peop" in ss) # True print(" sea" in ss) # True ``` ---- ### Indexing & slicing <font size=5> 後面的單元會更詳細介紹 slicing,這邊先提供參考 </font> ```python ss = "Hello, Foo Bar" print(ss[0]) # "H" print(ss[-1]) # "r" print(ss[1:3]) # "el" print(ss[:3]) # "Hel" print(ss[-3:]) # "Bar" print(ss[4::-1]) # "olleH" ``` --- ## 格式化你的字串 <font size=6> 方便將不同變數儲存的內容,組合成一個完整的句子 </font> ```python name = "Yoyo" print(f"你好,{name}") # 你好,Yoyo # 實務上的應用之一 formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s [at %(filename)s:%(lineno)d]") handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger() logger.addHandler(handler) logger.setLevel(logging.INFO) logger.info("Hello Python") # 2024-04-30 20:03:00 [INFO] Hello Python [at main.py:10] ``` --- ## 幾種不同格式化的方法 #### % - 過時的方法 `print("你好,%s" % name)` #### .format - 還行 `print("你好,{}".format(name))` #### f-string - 最新流行 `print(f"你好,{name}")` --- ## .format ```python name = "Yoyo" year = 18 print("我是{},今年{}歲".format(name, year)) # 我是Yoyo,今年18歲 print("我是{1},今年{0}歲".format(year, name)) print("我是{name},今年{year}歲".format(name=name, year=year)) # 格式化小數點 height = 159.66666666 print("我身高{:.1f}公分".format(height)) # 我身高159.7公分 ``` --- ## Padding ---- 強迫症發作... ![截圖 2024-04-25 下午3.29.34](https://hackmd.io/_uploads/BJMuLtPbA.png =60%x) ---- 排序亂掉 ![截圖 2024-04-25 下午3.22.53](https://hackmd.io/_uploads/SytWrFvbR.png =20%x) --- ## Padding - 向右看~~起!! ```python print(f"新兵 {1:02} 號,身上有 {1:7} 塊美金!") print(f"新兵 {2:02} 號,身上有 {203:7} 塊美金!") print(f"新兵 {13:02} 號,身上有 {9885.2:7,} 塊美金!") ``` ![截圖 2024-04-25 下午4.32.54](https://hackmd.io/_uploads/B1dHS9PWR.png =70%x) 酥胡~~ ---- ![截圖 2024-04-25 下午3.55.28](https://hackmd.io/_uploads/BJQF3YP-R.png =15%x) 整齊了~~ ---- #### 向左向中看~~齊! ```python print(f"The {'world':<10} is beautiful") print(f"The {'world':^10} is beautiful") print(f"The {'world':@^10} is beautiful") ``` --- ### f-string 黑魔法 ```python a = "Yeah" b = 123 c = 1.234567 print(f"{a=} / {b=} / {c=:10.5f}") # a='Yeah' / b=123 / c= 1.23457 ``` --- <!-- .slide: data-background="https://hackmd.io/_uploads/Sk6dWsdb0.jpg" --> # 感謝大家的收聽~ 學海無涯,學習 Python 的前方依舊是漫漫長路 --- ## References - [Colab](https://colab.research.google.com/drive/1nQmPA6uaguR3tUpd5zmNpoND82sFGPbv?usp=sharing)
{"contributors":"[{\"id\":\"b1e00459-ddb2-479e-b757-9f04a68f2ed8\",\"add\":4794,\"del\":550}]","slideOptions":"{\"font-size\":\"12px\"}","description":"","title":"文字字串講師"}
    106 views