字串處理入門

Python 中的正規表示法

Maria Eugenia Inzaugarat

Data Scientist

你將學到

  • 字串操作

    • 例如取代、尋找特定子字串
  • 字串格式化

    • 例如在樣板中插入字串
  • 基礎與進階正規表示式

    • 例如在字串中找複雜樣式
Python 中的正規表示法

為何重要

  • 清理資料集,為文字探勘或情緒分析做準備

  • 處理電子郵件內容,提供給機器學習演算法判斷是否為垃圾信

  • 剖析並擷取網站中的特定資料來建立資料庫

Python 中的正規表示法

字串

  • 由一連串字元組成

  • 引號

my_string = "This is a string"
my_string2 = 'This is also a string'
my_string = 'And this? It's the wrong string'
my_string = "And this? It's the correct string"
Python 中的正規表示法

更多字串

  • 長度
my_string = "Awesome day"

len(my_string)
11
  • 轉為字串
str(123)
'123'
Python 中的正規表示法

串接

  • 串接:+ 運算子
my_string1 = "Awesome day"
my_string2 = "for biking"
print(my_string1+" "+my_string2)
Awesome day for biking
Python 中的正規表示法

索引

  • 中括號表示法

my_string = "Awesome day"
print(my_string[3])
s

 

print(my_string[-1])
y
Python 中的正規表示法

切片

  • 中括號表示法

my_string = "Awesome day"
print(my_string[0:3])
Awe

 

print(my_string[:5])
print(my_string[5:])
Aweso
me day
Python 中的正規表示法

步長

  • 指定步長

my_string = "Awesome day"
print(my_string[0:6:2])
Aeo

 

print(my_string[::-1])
yad emosewA
Python 中的正規表示法

一起來練習吧!

Python 中的正規表示法

Preparing Video For Download...