Python 文字列中の大文字の数を出力

Document 对象参考手册Python3 例

このプログラムは、指定された文字列中の大文字の数を計算して出力します。

例

def count_uppercase_letters(s):
    count = 0
    for char in s:
        if char.isupper():
            count += 1
    return count

# サンプル文字列
sample_string = "Hello World! This is a Test."
uppercase_count = count_uppercase_letters(sample_string)
print(f"The number of uppercase letters in the string is: {uppercase_count}")

コードの解説:

  1. 関数を定義しますcount_uppercase_letters、それは文字列を受け取りますsをパラメータとして。
  2. カウンターを初期化しますcountを0にします。
  3. 使用しますforループで文字列の各文字を反復処理しますchar。
  4. 使用しますchar.isupper()メソッドで現在の文字が大文字かどうかを確認します。もしそうなら、カウンターはcount1増加します。
  5. ループが終了したら、カウンターの値を返します。
  6. サンプル文字列を定義しますsample_string、そして呼び出しますcount_uppercase_letters関数を使ってその中の大文字の数を計算します。
  7. 使用しますprint関数で結果を出力します。

出力結果:

The number of uppercase letters in the string is: 4

Document 对象参考手册Python3 例

その他の拡張