Python程序输入一个字符串并查找字母和数字的总数
给定一个字符串str1,我们必须计算字母和数字的总数。
示例
Input:
"Hello World!"
Output:
Letters: 10
Digits: 0
Input:
"[email protected]"
Output:
Letters: 5
Digits: 3方法1:
(手动)通过使用条件语句检查字符串的每个字母以及一系列字母和数字。
print("Input a string: ")
str1 = input()no_of_letters, no_of_digits = 0,0
for c in str1:
if (c>='a' and c<='z') or (c>='A' and c<='Z'):
no_of_letters += 1
if c>='0' and c<='9':
no_of_digits += 1
print("Input string is: ", str1)
print("Total number of letters: ", no_of_letters)
print("Total number of digits: ", no_of_digits)输出结果
RUN 1: Input a string: Hello World! Input string is: Hello World! Total number of letters: 10 Total number of digits: 0 RUN 2: Input a string: [email protected] Input string is: [email protected] Total number of letters: 5 Total number of digits: 3
方法2:
通过使用isalpha()和isnumeric()方法
print("Input a string: ")
str1 = input()no_of_letters, no_of_digits = 0,0
for c in str1:
no_of_letters += c.isalpha()
no_of_digits += c.isnumeric()print("Input string is: ", str1)
print("Total number of letters: ", no_of_letters)
print("Total number of digits: ", no_of_digits)输出结果
RUN 1: Input a string: Hello World! Input string is: Hello World! Total number of letters: 10 Total number of digits: 0 RUN 2: Input a string: [email protected] Input string is: [email protected] Total number of letters: 5 Total number of digits: 3
热门推荐
10 医院探望朋友祝福语简短
11 毕业祝福语简短女朋友
12 春节虎年爸妈祝福语简短
13 儿童毕业祝福语 简短6
14 开工仪式横幅祝福语简短
15 孩子日常祝福语大全简短
16 清晨寄语诗句祝福语简短
17 结婚送亲认亲祝福语简短
18 虎年喝酒拜年祝福语简短