iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0
Python

探索 Python 世界:從語法基礎到圖像魔法系列 第 8

探索 Python 世界:從語法基礎到圖像魔法 Day8

  • 分享至 

  • xImage
  •  

字串檢測函數、字串搜尋函數、字串編修函數

字串檢測函數

字串類別提供了一系列的函數,可讓user用來檢測字串是否具有某些性質

  • 字串檢測函數:
    s.isupper(), s.islower() 檢測字串 s 是否全部為大寫/小寫
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687C6gqxqAmKp.png
    s.startswith(s1), s.endswith(s1) 檢測字串 s 是否以字元 s1 開頭/結尾
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687JWZQLGixZb.png
    s.istitle() 檢測字串 s 裡每一單字的第一個字母是否為大寫
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687daIGXTZVCe.png
    s.isalpha() 檢測字串 s 是否全為英文
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687yPy770vVRe.png
    s.isdigit() 檢測字串 s 是否全為數字
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687cHH3cRBtWM.png
    s.isalnum() 檢測字串 s 是否全為英文或數字
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687YNhbD3IxYj.png
    s.isidentifier() 檢測字串 s 是否為合法的識別字或關鍵字
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687JA1JvqHHCf.png
    s.isspace() 檢測字串 s 是否全為空格
    https://ithelp.ithome.com.tw/upload/images/20240916/201686873vzwGynMv3.png

  • 字串搜尋函數:
    s1.count(s) 計算 s1 在字串 s 中的出現次數
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687xE0gANegtj.png
    s1.find(s) 找出字串 s 在 s1 中,首次出現的位置
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687iEkOqnvcHn.png
    s1.rfnd(s) 找出字串 s 在 s1 中,最後出現的位置
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687NYqHRUPJP9.png

  • 字串編修函數:
    s.replace(old,new) 將字串 s 的 old 部分置換成 new
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687y6wSZcngs7.png
    s.lstrip(chars) 將字串 s 左側開始刪除 chars 指定的字元,直到找不到指定字元為止(若未指定 chars 將刪除空白字元)
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687xtccP23J3j.png
    s.rstrip(chars) 跟 s.lstrip() 有相同原則,不過是從右側開始刪除指定字元
    https://ithelp.ithome.com.tw/upload/images/20240916/2016868756CiuzQVMW.png
    s.center(w) 將 s 以 w 個欄位置中排列
    https://ithelp.ithome.com.tw/upload/images/20240916/2016868754421xb7Au.png
    s.ljust(w), s.rjust() 將 s 以 w 個欄位靠左/靠右排列
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687koupNQIPnU.png
    s.zfill(w) 以 w 個欄位靠右顯示 s ,多於欄位補0(z = zero)
    https://ithelp.ithome.com.tw/upload/images/20240916/201686877mJjDRO4Kf.png
    s.join([s1, s2,..., sn]) 將字串 s1,s2,...,sn 用字串 s 連接起來
    https://ithelp.ithome.com.tw/upload/images/20240916/20168687XboaqmRLIe.png
    補充:利用字串 s 呼叫上述的字串函數之後,s 字串的內容不會被改變,而是回傳一個新字串

參考資料:https://docs.python.org/zh-tw/3/tutorial/index.html


上一篇
探索 Python 世界:從語法基礎到圖像魔法 Day7
下一篇
探索 Python 世界:從語法基礎到圖像魔法 Day9
系列文
探索 Python 世界:從語法基礎到圖像魔法20
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言