Python
Posted on 2023-09-06

Introduction

今天在解題的時候在想有沒有可以使用 dictionary 的方法來刪除某一些文字, 以前都是直接使用 for 使用 isalnum 來區別標點符號

use isalnum

s = ''.join(c for c in s if c.isalnum())

maketrans method

就如前面所說的,我想像中的方法是有沒有一個 “dictionary” 來看到底需要被替換或著是被刪除的文字,廢話不多說直接上 code

import string

translator = str.maketrans('', '', string.punctuation)

print(translator) # {33: None, 34: None, 35: None, 36: None, 37: None, 38: None, 39: None, 40: None, 41: None, 42: None, 43: None, 44: None, 45: None, 46: None, 47: None, 58: None, 59: None, 60: None, 61: None, 62: None, 63: None, 64: None, 91: None, 92: None, 93: None, 94: None, 95: None, 96: None, 123: None, 124: None, 125: None, 126: None}

maketrans 會創建 !"#$%&'()*+,-./:;<=>?@[\]^_{|}~對到None` 的 dictionary

translate method

既然都有這個 dictionary 接下來就要進行替換的動作了!

text = "Madam I'm Adam"

print(text.translate(translator)) # Madam Im Ada
Made with ❤️ by Jiawei Hong