在前面幾篇,我們學會了字串的基本操作,以及了解 f-string讓我們想怎麼顯示就怎麼顯示。
那麼今天我們就來點「魔法小絕招」吧!

絕招一:split(),一句話變清單!

你可以決定想要從哪個符號切開來,比如我今天從「 , 」切開,像這樣把一長串的字串切開變成一個清單。

line = “apple,banana,grape”
fruits = line.split(“,”)
print(fruits)
# [‘apple’, ‘banana’, ‘grape’]

又或者從空白 space 切開。

line = “I like stanCode”
token = line.split(“”)
print(token)
# [‘I’, ‘like’, ‘stanCode’]

絕招二:join(),把清單變一句話!

跟 split() 相反,join() 可以把一堆字合起來,中間用你指定的符號連接:

words = [‘I’, ‘study’, ‘Python’, ‘in’, ‘stanCode’]
result = ” “.join(words)
print(result)
# I study Python in stanCode

絕招三:strip(),一鍵去除空白和符號!

在處理文章的時候,前前後後都會有很多多餘的空白、換行字元、奇怪符號等等的,直接通通交給 strip() 就可以處理了!

text = ”      How are you?         “
print(text.strip())
# How are you?

如果是想把裡面的符號刪掉,也是可以的!

text = “I’$m f$i$n$e, tha$nk yo$$u.”
print(text.strip(“$”))
# I’m fine, thank you.

絕招四:判斷字串內的類型

想知道現在的字串內是英文還是數字,可以直接用簡單的絕招問!交給電腦幫你確認吧~

name = “Karel”
print(name.isalpha())
# True,只包含字母

score = “95”
print(score.isdigit())
# True,只包含數字

blank = ” “
print(blank.isspace())
# True,全是空白

絕招五:判斷開頭與結尾是什麼!

startswith() 和 endswith() 可以直接檢查這段字串的頭尾是不是你詢問的!

file = “stanCodoshop.py”
print(file.endswith(“.pt”))
# True

url = https://stancode.tw/
print(url.startswith(“https”))
# True

絕招六:replace() 一鍵取代!

當我們在一篇文章中,想要一次替換掉某個字的時候,就可以直接使用 replace() 來全部替換唷!
字串.replace(要被換掉的內容, 更新後的內容)

text = “I hate to study Coding, and also hate Python”
new_text = text.replace(“hate”, “love”)
print(new_text)
# I love to study Coding, and also love Python

結語
這些字串處理的絕招,雖然看起來簡單,卻是在字串當中最實用的工具們,一定要好好記住哦!

Close Menu