python 目次 - ray88’s diary
■文字列の前後にある空白や改行コード、カンマやピリオド等を取り除きたいとき
■stripメソッド:文字列の先頭と末尾にある余分な文字等を取り除く
■rstripメソッド:末尾にある余分な文字等を取り除く
■サンプルコード①
#文字列を設定 str_sample = " hello \n" #先頭と末尾の不要な空白および改行コードを取り除く #不要な文字(空白)が連続している場合は順に不要な文字を削っていく answer = str_sample.strip() print("置き換え後文字列:" + answer) #文字列を設定 str_sample = "abc..........." #先頭と末尾の不要な空白および改行コードを取り除く answer = str_sample.rstrip(".") print("置き換え後文字列:" + answer)
出力結果
■サンプルコード②
文字列を設定 str_sample = "2,3,4," #末尾にあるカンマを取り除く answer = str_sample.strip(".,\n") print("置き換え後文字列:" + answer) #文字列を設定 str_sample = "Hello World.\n" #先頭と末尾の不要な空白および改行コードを取り除く answer = str_sample.rstrip(".,\n") print("置き換え後文字列:" + answer)
出力結果
■サンプルコード③
注意が必要なケース:以下の様な場合は「.jpeg」に含まれる文字は末尾から全て取り除かれてしまう。
#文字列を設定 str_sample = "dog.peg.jp" answer = str_sample.strip(".jpeg") print("置き換え後文字列:" + answer)
出力結果