RegularExpression
string Formatting 字串格式
- 可以修改字串所顯示的格式
- 將字串用包起來表示要置換的部分
a = 200
b = 8.9
c = 'hello'
'{} {} {}'.format(a,b,c)
coord = (8,9) //1個tuple裡面有兩個值
'X={0[0]} Y={0[1]}'.format(coord) //0代表採用第一個參數, [0]代表參數中的第0個元素
a = 33
b = 19
'percentage = {:.2%}'.format(a/b) //percentage = 57.58% 兩位數的小數點
d = datetime.datetime(2020,1,1,12,33,43)
':%Y-%m-%d %H:%M:%S'.format(d) //2022-01-01 12:33:43
Regular Expression 正規表示法
- 用來抓取符合指定規則之字串的方法
- Python有內建re模組來操作regular expression
- 常用來操作regular expression的函數有match(),search(),findall()
- match:從第一個字元開始比對是否符合pattern
- search:尋找任何地方有符合pattern的字串
- findall:尋找所有滿足pattern的字串
- 網路上有輔助工具Pythex
//-----match()
import re
txt = 'hello, hey, hi, Salaheyo'
x = re.match('\w*', txt)
x
//-----search()
phonenumber = "(02)-222-1234, 03-333-1234"
regex = "\w{2}-\w{3}-\w{4}"
search_obj = re.search(regex, phonenumber)
if search_obj:
print(search_obj)
print('Valid phone number')
else:
print('Invalid Phone number')
//-----findall()
import re
txt = 'hello 23 hi 11 how are 889'
pattern ='\d+' //字串內所有數字抓出來
x = re.findall(patttern, txt)
x //['23','11','889']