パイソン 弦 ストリップ() これは、Python プログラミング言語の組み込み関数であり、(渡された文字列引数に基づいて) 先頭文字と末尾文字の両方が削除された文字列のコピーを返します。この記事では、strip() メソッドの多くの機能と使用例を検討し、Python プログラムでこのメソッドをうまく使用する方法を完全に理解できるようにします。
Pythonのstrip()メソッドの構文
構文: string.strip([文字])
パラメータ: オプションのパラメータは 1 つだけです。 文字 – 削除する文字セットを指定する文字列。オプションの chars パラメータが指定されていない場合は、先頭と末尾の空白がすべて文字列から削除されます。
戻り値: 先頭文字と末尾文字の両方を削除した文字列のコピーを返します。
Python Strip() 関数の目的
開発者が文字列の先頭または末尾から文字または空白を削除したい場合、Strip() 関数を使用します。 パイソン 便利です。詳しく見てみましょう:
- ストリップ() 関数は、ストリング() 関数の引数として指定された文字の先頭または末尾から文字を削除するのに役立ちます ()。
- 文字列に空白がなく、文字引数が指定されていない場合は、文字列がそのまま返されます。
- テキストの先頭と末尾の空白を削除することも有益です。
- 文字列に空白が含まれており、文字引数が指定されていない場合、文字列は空白を離散化した後に返されます。
Python の Stringstrip() の例
で パイソン 、strip()>メソッドは先頭と末尾を削除するために使用されます 空白文字 (スペース、タブ、改行) を文字列から取得します。空白文字が削除された新しい文字列を返します。元の文字列は変更されません。
例
配列cの文字列
Python3
my_string>=> ' Hello, world! '> stripped_string>=> my_string.strip()> > print>(stripped_string)> |
>
>
出力
Hello, world!>
Python Strip() 関数による文字列の除去
この例では、Python を使用します。 ストリングトリム 文字列を使用し、strip() 関数を 弦 しかも紐なしで。
Python3
string>=> ''' geeks for geeks '''> > # prints the string without stripping> print>(string)> > # prints the string by removing leading and trailing whitespaces> print>(string.strip())> > # prints the string by removing geeks> print>(string.strip(>' geeks'>))> |
>
>
出力
geeks for geeks geeks for geeks for>
Python Strip() 関数を使用して特定の文字を削除する
この例では、 Python 文字列 Trim では、strip() 関数を使用して文字列から特定の文字セットを削除しました。
Python3
# Python Program to demonstrate use of strip() method> > str1>=> 'geeks for geeks'> # Print the string without stripping.> print>(str1)> > # String whose set of characters are to be> # remove from original string at both its ends.> str2>=> 'ekgs'> > # Print string after stripping str2 from str1 at both its end.> print>(str1.strip(str2))> |
>
>
出力
geeks for geeks for>
Python Strip() 関数を使用して空白を削除する
この例では、 Python 文字列 Trim では、strip() 関数を使用して文字列の両端から空白を削除しました。
Python3
# Python Program to demonstrate use of strip() method without any argument> str1>=> ''' geeks for geeks '''> > # Print the string without stripping.> print>(str1)> > # Print string after removing all leading> # and trailing whitespaces.> print>(str1.strip())> |
>
>
入力
geeks for geeks>
出力
geeks for geeks>
Python Strip() 関数を使用して NewLine を削除する
この例では、Python String Trim を実行し、strip() 関数を使用して文字列を削除します。 改行文字 文字列から。
Python3
Java文字列
string>=> '
Hello, World!
'> new_string>=> string.strip()> print>(new_string)> |
>
>
出力
Hello, World!>
実用化
指定された文字列の先頭と末尾から単語 the の出現を削除します。 Python String Trimを行います。
パイソン
# Python3 program to demonstrate the practical application> # strip()> > string>=> ' the King has the largest army in the entire world the'> > # strip function works on characters and removes characters till it sees,> # the last or beginning characters mentioned in the function has been removed> print>(string.strip(>' eht'>))> |
>
>
入力
the King has the largest army in the entire world the>
出力
King has the largest army in the entire world>