Python 文字列中の大文字の数を出力
このプログラムは、指定された文字列中の大文字の数を計算して出力します。
例
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}")
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}")
コードの解説:
- 関数を定義します
count_uppercase_letters、それは文字列を受け取りますsをパラメータとして。 - カウンターを初期化します
countを0にします。 - 使用します
forループで文字列の各文字を反復処理しますchar。 - 使用します
char.isupper()メソッドで現在の文字が大文字かどうかを確認します。もしそうなら、カウンターはcount1増加します。 - ループが終了したら、カウンターの値を返します。
- サンプル文字列を定義します
sample_string、そして呼び出しますcount_uppercase_letters関数を使ってその中の大文字の数を計算します。 - 使用します
print関数で結果を出力します。
出力結果:
The number of uppercase letters in the string is: 4その他の拡張
Python3 例