Python 練習例17
問題:1行の文字を入力し、その中の英文字、スペース、数字、その他の文字の個数をそれぞれ集計します。
プログラム分析:while または for 文を利用します。条件は入力された文字が '\n' でないことです。
例(Python2.x) - while ループを使用
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import string
s = raw_input('文字列を1つ入力してください:\n')
letters = 0
space = 0
digit = 0
others = 0
i=0
while i < len(s):
c = s[i]
i += 1
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print 'char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others)
例(Python3.x) - for ループを使用
#!/usr/bin/python3
import string
s = input('文字列を1つ入力してください:\n')
letters = 0
space = 0
digit = 0
others = 0
for c in s:
if c.isalpha():
letters += 1
elif c.isspace():
space += 1
elif c.isdigit():
digit += 1
else:
others += 1
print ('char = %d,space = %d,digit = %d,others = %d' % (letters,space,digit,others))
上記の例の出力結果は次の通りです:
请输入一个字符串: 123サンプルc kdf235*(dfl char = 13,space = 2,digit = 6,others = 2その他の拡張