銀河鉄道

【Python】先頭,末尾,両端の空白を削除する|.strip

サムネイル
[Python]stripspace

半角スペース・全角スペース・タブ・改行を削除する|左か右か両端か

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

VBAPython
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.

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧