python输入一个字符一个数字_Python程序输入一个字符串并查找字母和数字的总数...
发布日期:2021-06-24 16:28:40 浏览次数:2 分类:技术文章

本文共 1326 字,大约阅读时间需要 4 分钟。

给定一个字符串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

转载地址:https://blog.csdn.net/weixin_33826897/article/details/113991178 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:vb中如何创建mysql表_在VB程序中实现新建一个新的access数据库
下一篇:memset 线程安全_多线程同步技术之互斥量、信号量

发表评论

最新留言

网站不错 人气很旺了 加油
[***.192.178.218]2024年04月10日 22时44分02秒