📌  相关文章
📜  Python程序在不使用内置函数的情况下计算大小写字符

📅  最后修改于: 2022-05-13 01:54:25.431000             🧑  作者: Mango

Python程序在不使用内置函数的情况下计算大小写字符

给定一个包含大写和小写字符的字符串。任务是在不使用内置函数的情况下计算其中的大小写字符数。

使用isupper()islower()函数可以轻松地计算字符串的大小写字符,请参阅this。但是在没有任何内置函数的帮助下做同样的事情是非常令人兴奋的。让我们看看如何做到这一点:

例子 :

Input : Introduction to Python
Output : Lower Case characters : 18 Upper case characters : 2

Input :  Welcome to GeeksforGeeks
Output : Lower Case characters : 19  Upper case characters: 3


以下是上述想法的实现:

# Python3 program to count upper and
# lower case characters without using
# inbuilt functions
def upperlower(string):
  
    upper = 0
    lower = 0
  
    for i in range(len(string)):
          
        # For lower letters
        if (ord(string[i]) >= 97 and
            ord(string[i]) <= 122):
            lower += 1
  
        # For upper letters
        elif (ord(string[i]) >= 65 and
              ord(string[i]) <= 90):
            upper += 1
  
    print('Lower case characters = %s' %lower,
          'Upper case characters = %s' %upper)
  
# Driver Code
string = 'GeeksforGeeks is a portal for Geeks'
upperlower(string)
输出:
Lower case characters = 27 Upper case characters = 3

替代方法:-

s = "The Geek King"
l,u = 0,0
for i in s:
    if (i>='a'and i<='z'):
          
        # counting lower case
        l=l+1                 
    if (i>='A'and i<='Z'):
          
        #counting upper case
        u=u+1   
          
print('Lower case characters: ',l)
print('Upper case characters: ',u)
输出:
Lower case characters:  8
Upper case characters:  3