python 文字列から半角全角の空白とタブを除去する

python 文字列から半角全角の空白とタブを除去する

pythonで、文字列から半角空白を除去するサンプルコードを記述してます。パッケージ「re」を使用して、正規表現を使います。pythonのバージョンは3.10.0を使用してます。

環境

  • OS windows11 home 64bit
  • python 3.10.0

半角全角の空白とタブを除去

半角全角の空白とタブを除去には、「re」をパッケージを使用して正規表現を使用します。

import re

txt = " he l l  o wo    r   l d "

result = re.sub(r"[\u3000 \t]", "", txt)

print(result) # helloworld
print(txt) #  he l l  o wo    r   l d 

「split」でも除去することは可能です。

import re

txt = " he l l  o wo    r   l d "

result = ''.join(txt.split())

print(result) # helloworld
print(txt) #  he l l  o wo    r   l d 

「translate」を使用することも可能です。

txt = " he l l  o wo    r   l d "

t = str.maketrans({
  '\u3000': '',
  ' ': '',
  '\t': ''
})

result = txt.translate(t)

print(result) # helloworld
print(txt) #  he l l  o wo    r   l d