【Python】文字列の先頭と末尾にあるスペース、空白文字を削除する
489 語
2 分
【Python】文字列の先頭と末尾にあるスペース、空白文字を削除する
はじまり

リサちゃん
さーて、今回もちょっとしたツールを作るかあ

リサちゃん
今回は、こいつらを作ろう。
今回は、こいつらを作ろう。
- 先頭にある空白文字を削除する。
- 末尾にある空白文字を削除する。
- 先頭および末尾にある空白文字を削除する。
今回のソース
こちらが今回のソースになります。
末尾にある空白文字を削除する関数が、remove_tail_sapces()、
先頭にある空白文字を削除する関数が、remove_head_sapces()、
先頭および末尾にある空白文字を削除する関数が、remove_spaces_at_head_and_tail()
になります。
src.py:
def remove_tail_sapces(word : str, spaces : list = [" ", " "]) -> str: word_removed_space = "" if len(word) == 0: word_removed_space = word elif word[len(word) - 1] in spaces: word_removed_space = word[0:len(word) - 1] print("'{}'".format(word_removed_space[0:len(word) - 1])) word_removed_space = remove_tail_sapces(word_removed_space, spaces) else: word_removed_space = word return word_removed_space
def remove_head_sapces(word : str, spaces : list = [" ", " "]) -> str: word_removed_space = "" if len(word) == 0: word_removed_space = word elif word[0] in spaces: word_removed_space = word[1:len(word)+1] # invisible head character if head space is nothing print("'{}'".format(word_removed_space[1:len(word)])) word_removed_space = remove_head_sapces(word_removed_space, spaces) else: word_removed_space = word return word_removed_space
def remove_spaces_at_head_and_tail(word : str, spaces : list = [" ", " "]) -> str: word_tail_removed = remove_tail_sapces(word, spaces) word_both_removed = remove_head_sapces(word_tail_removed, spaces) return word_both_removed
keyword = " node.js "actual = remove_spaces_at_head_and_tail(keyword, [" ", " "])print(actual)出力
' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js '' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js'' node.js''node.js''ode.js'node.js補足
各関数にある引数spacesのリストの中身を変更・追加すれば、先頭と末尾にある不要な文字を変更・追加する事ができます。
おしまい

リサちゃん
よっしゃあ、今回もできたぜえ!
以上になります!
記事を共有
この記事が役に立ったなら、ぜひ他の人と共有してください!
【Python】文字列の先頭と末尾にあるスペース、空白文字を削除する
https://endorphinbath.com/posts/python-remove-spaces-head-and-tail/ 関連記事 スマート
1
【Python】複数の区切り文字を指定して文字列を配列に分割する
Code Pythonで文字列を配列に分割するスクリプトを掲載します。分割文字は配列で指定するように作っています。
2
【Python】.pyファイルにある関数とメソッドを全て取得する
Code Pythonで.pyファイルの中に記述されている関数およびメソッドを全て取得するスクリプトを掲載します。
3
【Python】Pydanticのvalidatorが非推奨だからfield_validatorを使って2段階バリデーションを実装する
Code @validatorはdeprecatedになってるし、@field_validatorにはpreとかalwaysフラグが無いから、from pydantic.functional_validators import field_validatorでインポートしたfield_validatorを使用する方法と、BeforeValidatorとAfterValidatorをAnnotateの中に入れる実装方法を試した。
4
【Python】シェル上で出力した文字列で濁点が分かれてしまった文字(結合文字)を濁音に直すスクリプト
Code シェル上でファイル名などを出力した際に、バがバになってしまう場合があります。それをいちいち手作業で直すのがしんどいので、直してくれるスクリプトを作りました。テストコードもあります。
5
【Python】1つのファイル内における関数の依存関係をMermaidの書式で出力する
Code 1つのファイル内のクラス図の依存関係を描画するために、MarkdownのMermaid書式で出力するPythonスクリプトを作りました。
ランダム記事 ランダム