【Python】複数の区切り文字を指定して文字列を配列に分割する
226 語
1 分
【Python】複数の区切り文字を指定して文字列を配列に分割する
はじまり

リサちゃん
よーし、今回は区切り文字を複数指定して、文字列を配列に変換するスクリプトを作るぞー。`str.split`だと文字を一つしか指定できないからねえ。
今回のソース
get_words_by_seperators()がメイン処理になります。
get_indices_by_seperators()で区切り文字があるインデックスを取得して、
get_words_by_indices()でそのインデックスをによって文字列を配列に変換します。
src.py:
def get_indices_by_seperators(word : str, seperators : list = [",", "、"]) -> list: sep_indices = [] for sep in seperators: start = 0 sep_index = 0 while sep_index != -1: sep_index = word.find(sep, start) if sep_index != -1: sep_indices.append(sep_index) start = sep_index + 1 sep_indices.append(len(word)) print(sep_indices) sep_indices.sort() print(sep_indices) return sep_indices
def get_words_by_indices(word : str, indices : list) -> list: start = 0 words = [] for i in indices: words.append(word[start:i]) start = i + 1 print(words) return words
def get_words_by_seperators(word : str, seperators : list = [",", "、"] , spaces : list = [" ", " "]) -> list: indices = get_indices_by_seperators(word, seperators) words = get_words_by_indices(word, indices) words_without_space = [] for word in words: words_without_space.append(remove_spaces_at_head_and_tail(word, spaces)) print(words_without_space) return words_without_space
keyword = "python, node.js 、 gollila ,web"actual = get_words_by_seperators(keyword)print(actual)出力:
[6, 26, 16, 30][6, 16, 26, 30]['python', ' node.js ', ' gollila ', 'web']' node.js''ode.js'' gollila''ollila'['python', 'node.js', 'gollila', 'web']['python', 'node.js', 'gollila', 'web']おしまい

リサちゃん
ふい〜、今回もおわり〜。
以上になります!
記事を共有
この記事が役に立ったなら、ぜひ他の人と共有してください!
【Python】複数の区切り文字を指定して文字列を配列に分割する
https://endorphinbath.com/posts/python-string-to-list-by-multi-seperator/ 関連記事 スマート
1
【Python】文字列の先頭と末尾にあるスペース、空白文字を削除する
Code Pythonで文字列の先頭と末尾にスペース(空白文字)が混じっていることがあります。そのスペースを削除するスクリプトを掲載します。
2
【Python】シェル上で出力した文字列で濁点が分かれてしまった文字(結合文字)を濁音に直すスクリプト
Code シェル上でファイル名などを出力した際に、バがバになってしまう場合があります。それをいちいち手作業で直すのがしんどいので、直してくれるスクリプトを作りました。テストコードもあります。
3
【Python】pytestで同じディレクトリのモジュールをimportして、"ModuleNotFoundError: No module named"を出さなくする
Code Pythonスクリプトをpytestするとき、"ModuleNotFoundError: No module named"が表示されてしまった場合、この記事の方法でそのエラーが解決するかも。
4
【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の中に入れる実装方法を試した。
5
【Python】.pyファイルにある関数とメソッドを全て取得する
Code Pythonで.pyファイルの中に記述されている関数およびメソッドを全て取得するスクリプトを掲載します。
ランダム記事 ランダム