【Python】先頭,末尾,両端の空白を削除する|.strip
作成日:2025-10-05
更新日:2025-10-06

半角スペース・全角スペース・タブ・改行を削除する|左か右か両端か
def trim_whitespace(text: str, mode: str = "B") -> str:
"""
Remove whitespace characters (half/full-width, tabs, newlines)
モード:
"L" = left only
"R" = right only
"B" = both sides (default)
"""
if not isinstance(text, str):
return text
mode = mode.upper()
text = text.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
full_space = ' '
if mode == "L":
text = text.lstrip()
while text.startswith(full_space):
text = text[1:]
elif mode == "R":
text = text.rstrip()
while text.endswith(full_space):
text = text[:-1]
else: # "B"
text = text.strip()
while text.startswith(full_space):
text = text[1:]
while text.endswith(full_space):
text = text[:-1]
return text
使用例
print(trim_space(" ABC ")) # → 'ABC'
print(trim_space(" ABC ", "L")) # → 'ABC '
print(trim_space(" ABC ", "R")) # → ' ABC'
Compare VBA and Python
VBA | Python |
---|---|
LTrim , RTrim , Trim | .lstrip() , .rstrip() , .strip() |
Do While + Left$/Right$ | while text.startswith() / endswith() |
Variant扱い | Pythonは動的型なので型宣言不要 |
補足|isinstance()
この値が特定の型(クラス)かどうかを調べる
isinstance(object, type)
引数 | 意味 |
---|---|
object | 調べたいオブジェクト |
type | 型(または型のタプル) |
戻り値は True
/ False
。
例
x = "Hello"
print(isinstance(x, str)) # True(文字列だから)
print(isinstance(x, int)) # False(整数じゃないから)
型を複数まとめてチェックする
x = 3.14
print(isinstance(x, (int, float))) # True(どっちかに当たればOK)
type()
との違い
関数 | 用途 | 柔軟性 |
---|---|---|
type(x) | 正確な型を返す(厳密一致) | 厳しい |
isinstance(x, 型) | 継承関係も含めて判断 | やわらかい |
たとえば:
class Animal: pass
class Dog(Animal): pass
a = Dog()
print(type(a) == Animal) # False
print(isinstance(a, Animal)) # True(DogはAnimalを継承してる)
今回の文脈での意味
trim_space()
の中でこれを使ってたのは:
if not isinstance(text, str):
return text
つまり「もし text
が文字列じゃなかったら、
無理に処理せずそのまま返す」っていう安全ガード(防御的プログラミング)
| Whitespace|空白文字 |
| Generalization|汎用化 |
| Strip Method|stripメソッド |
| Full-width Space|全角スペース |
| Startswith|先頭判定 |
| Dynamic Typing|動的型付け |
| Trim|整える |
| Remove|取り除く |
| Strip|削ぎ取る |
Remove every space,
and the meaning becomes clear.
and the meaning becomes clear.
2025-10-05
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-
[Python]Excelto CSV 【Python】ExcelからCSVに書き出す|pandas,csv -
[Python]getdictionary 【Python】dictionaryから値を取得する2つの違い -
[Python]inString 【Python】指定の文字列が含まれているか|in -
[Python]pathlibfor extension 【Python】文字列から拡張子を取得して、文字列で返す|pathlib.Path.suffix -
[Python]list concatenation 【Python】配列(list)の結合|arr + arr , np.concatenate -
[Python]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com