Python程序输入字符串并查找字母和数字的总数

Given a string str1 and we have to count the total numbers of letters and digits.

给定一个字符串str1 ,我们必须计算字母和数字的总数。

Example:

例:

    Input: 
    "Hello World!"
    Output:
    Letters: 10
    Digits: 0

    Input: 
    "[email protected]"
    Output:
    Letters: 5
    Digits: 3

Method 1:

方法1:

(Manual) By checking each character of the string with a range of the letters and numbers using the conditional statement.

(手动)通过使用条件语句检查字符串中每个字母和数字范围的字符。

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)

Output

输出量

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

Method 2:

方法2:

By using isalpha() and isnumeric() methods

通过使用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)

Output

输出量

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://www.includehelp.com/python/program-to-input-a-string-and-find-total-number-of-letters-and-digits.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值