Python Practice Example 17
Problem:Input a line of characters, and count the number of English letters, spaces, digits, and other characters respectively.
Program analysis:Use a while or for statement, with the condition that the input character is not '\n'.
Example (Python 2.x) - Using a while loop
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import string
s = raw_input('Please enter a string:\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)
Example (Python 3.x) - Using a for loop
#!/usr/bin/python3
import string
s = input('Please enter a string:\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))
The output result of the above example is:
请输入一个字符串: 123examplec kdf235*(dfl char = 13,space = 2,digit = 6,others = 2Other extensions
Python 100 Examples