どうも、ちょげ(@chogetarou)です。
文字列の空白を全て削除する方法を紹介します。
方法
文字列の空白を全て削除する方法は、4つあります。
join() + split()
1つ目は、join()とsplit()を使う方法です。
まず、空文字(”)からjoin()を呼び出します。
そして、join()の引数で文字列からsplit()を呼び出します。
result = ''.join(text.split())
上記のjoin()は、split()を呼び出した文字列の空白を全て削除した文字列を返します。
使用例
text = " H e l l o, Pyth on"
result = ''.join(text.split())
print(result)
出力:
Hello,Python
replace()
2つ目は、replace()を使う方法です。
まず、文字列からreplace()を呼び出します。
そして、replace()の第1引数に空白の文字列、第2引数に空文字( ” )を指定します。
result = text.replace(' ', '')
上記のreplace()は、呼び出した文字列の空白を削除した文字列を返します。
もし、半角と全角の両方の空白を削除したい場合は、文字列からreplace()を2度呼び出します。
replace()のそれぞれの第1引数に半角と全角の空白を指定します。
そして、両方のreplace()の第2引数に空文字を指定します。
#最初のreplace()の第1引数に半角の空白を指定
#2番目のreplace()の第1引数に全角の空白を指定
result = text.replace(' ', '').replace(' ', '')
使用例
text = " H e l l o, Pyth on"
result = text.replace(' ', '')
print(result)
出力:
Hello,Python
translate()
3つ目は、translate()を使う方法です。
まず、stringをインポートします。
import string
次に、文字列からtranslate()を呼び出します。
translate()の引数でstrからmaketrans()を呼び出します。
そして、maketrans()の第1引数と第2引数に空文字、第3引数にstring.whitespace()を使います。
result = text.translate(str.maketrans('', '', string.whitespace))
上記のtranslate()は、呼び出した文字列の空白を全て削除した文字列を返します。
使用例
import string
text = " H e l l o, Pyth on"
result = text.translate(str.maketrans('', '', string.whitespace))
print(result)
出力:
Hello,Python
正規表現
4つ目は、正規表現を使う方法です。
まず、reをインポートします。
import re
次に、re.sub()を呼び出します。
re.sub()の第1引数に「r’\s+’」、第2引数に空文字を指定します。
そして、re.sub()の第3引数に文字列を指定します。
result = re.sub(r'\s+', '', text)
上記のre.sub()は、第3引数に指定した文字列の空白を全て削除した文字列を返します。
使用例
import re
text = " H e l l o, Pyth on"
result = re.sub(r'\s+', '', text)
print(result)
出力:
Hello,Python
まとめ
文字列の空白を全て削除する方法は、次の4つです。
- join()とsplit()を使う方法
result = ''.join(text.split())
- replace()を使う方法
result = text.replace(' ', '')
- translate()を使う方法
result = text.translate(str.maketrans('', '', string.whitespace))
- re.sub()を使う方法
result = re.sub(r’\s+’, ”, text)
コメント