Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonで文字列の長さを見つける(3つの方法)


文字列は、一連のUnicode文字であるPythonです。一度宣言すると、変更できません。この記事では、文字列の長さを見つけるためのさまざまな方法を説明します。

len()の使用

これが最も簡単な方法です。ここでは、len()という名前のライブラリ関数を使用します。文字列はパラメータとして関数に渡され、画面内の文字数を取得します。

str ="Tutorials"
print("Length of the String is:", len(str))

出力

上記のコードを実行すると、次の結果が得られます-

Length of the String is: 9

スライスの使用

文字列スライスアプローチを使用して、文字列内の各文字の位置をカウントできます。文字列内の位置の数の最終的なカウントは、文字列の長さになります。

str = "Tutorials"
position = 0
# Stop when all the positions are counted
while str[position:]:
   position += 1
# Print the total number of positions
print("The total number of characters in the string: ",position)

出力

上記のコードを実行すると、次の結果が得られます-

The total number of characters in the string: 9

join()とcount()の使用

join()およびcount()文字列関数も使用できます

str = "Tutorials"
#iterate through each character of the string
# and count them
length=((str).join(str)).count(str) + 1
# Print the total number of positions
print("The total number of characters in the string: ",length)

出力

上記のコードを実行すると、次の結果が得られます-

The total number of characters in the string: 9

  1. Pythonプログラムで文中の単語を数える

    この記事では、以下に示す問題ステートメントの解決策について学習します。 問題の説明 −文字列内の単語数を数えるために必要な文字列が与えられます アプローチ1-split()関数の使用 Split関数は、文字列を区切り文字としてスペースを使用して反復可能なリストに分割します。区切り文字を指定せずにsplit()関数を使用すると、デフォルトの区切り文字としてスペースが割り当てられます。 例 test_string = "Tutorials point is a learning platform" #original string print ("The orig

  2. 文字列内の単語の出現をカウントするPythonプログラム

    このチュートリアルでは、文字列に単語が出現する回数をカウントするプログラムを作成します。単語と文字列が与えられたら、文字列内の単語の頻度を計算する必要があります。 文字列があるとします私はプログラマーです。私は学生です。 そして、という言葉は 。これから作成するプログラムは、数値 2を返します。 単語が発生する 文字列内で2回。 以下の手順に従って、目標を達成しましょう。 アルゴリズム 1. Initialize the string and the word as two variables. 2. Split the string at spaces using the split()