Python Exercise Example 17
**Problem:** Enter a line of characters and count the English letters, spaces, digits, and other characters separately.
**Program analysis:** Use a while or for statement with the condition that the input character is not '\n'.
Example (Python2.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
'
char = %d,space = %d,digit = %d,others = %d
'
%
(
letters
,
space
,
digit
,
others
)
Example (Python3.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
(
'
char = %d,space = %d,digit = %d,others = %d
'
%
(
letters
,
space
,
digit
,
others
)
)
The output of the above example is:
Please enter a string:
123runoobc kdf235*(dfl
char = 13,space = 2,digit = 6,others = 2
Python 100 Examples