isupper (), islower (), lower (), upper () in Python and their applications

Counters | islower | isupper | Python Methods and Functions

In Python, isupper () — it is a built-in method used to process strings. 
The isupper () methods return "True" if all characters in the string are uppercase, otherwise it returns "False". 
This function is used to check if the argument contains any uppercase characters, such as:

 ABCDEFGHIJKLMNOPQRSTUVWXYZ 

Syntax :

  string.isupper ()   Parameters:  isupper () does not take any parameters  Returns:  1.True- If all characters in the string are uppercase. 2.False- If the string contains 1 or more non-uppercase characters. 

Examples:

 Input: string = 'GEEKSFORGEEKS' Output: True Input: string =' GeeksforGeeks' Output: False 

Errors and exceptions

  1. Returns "True" for spaces
  2. It takes no arguments, so it returns an error if a parameter is passed.
  3. Digits and characters return "True", only capital letter returns "false".

# Python code to implement isupper ()

 
# checking capital letters

string = 'GEEKSFORGEEKS'

print (string.isupper ())

  

string = ' GeeksforGeeks'

print (string.isupper ())

Output:

 True False 

ISLOWER ()

In Python islower () — it is a built-in method used to process strings. 
The islower () methods return "True" if all characters in the string are lowercase, otherwise it returns "False". 
This function is used to check if the argument contains any lowercase characters such as:

 abcdefghijklmnopqrstuvwxyz 

Syntax :

  string.islower ()   Parameters:  islower () does not take any parameters  Returns:  1.True- If all characters in the string are lower. 2.False- If the string contains 1 or more non-lowercase characters. 

Examples:

 Input: string = 'pythonengineering' Output: True Input: string =' GeeksforGeeks' Output: False 

Errors and exceptions

  1. Returns "True" for spaces
  2. It takes no arguments, so it returns an error if a parameter is passed.
  3. Digits and characters return "True", only a lowercase letter returns "false".

# Python code to implement isupper ()

 
# checking lowercase letters

string = 'pythonengineering'

print (string.islower ())

  

string = 'GeeksforGeeks'

print ( string.islower ())

Output:

 True False 

below ()

In Python, lower () — it is a built-in method used to process strings. 
The lower () methods return a lowercase string from a given string. It converts all uppercase letters to lowercase. If no uppercase characters exist, the original string is returned.

Syntax :

  string.lower ()   Parameters:  lower () does not take any parameters  Returns:  It converts the given string in into lowercase and returns the string. 

Examples:

 Input: string = 'GEEKSFORGEEKS' Output: pythonengineering Input: string =' GeeksforGeeks' Output: pythonengineering 

Errors and exceptions

  1. It takes no arguments, so it returns an error if a parameter is passed.
  2. The numbers and characters returned are returned as-is. After converting to lowercase, only the uppercase letter is returned.

# Python code to implement lower ()

 
# Checking lowercase letters

string = 'GEEKSFORGEEKS'

print (string.lower ())

 

string = 'GeeksforGeeks'

print (string.lower ())

Output:

 pythonengineering pythonengineering 

Top ()

In Python, upper () — it is a built-in method used to process strings. 
The upper () methods return the uppercase string from the given string. It converts all lowercase letters to uppercase. If no lowercase characters exist, the original string is returned.

Syntax :

  string.upper ()   Parameters:  upper () does not take any parameters  Returns:  It converts the given string in into uppercase and returns the string. 

Examples:

 Input: string = 'pythonengineering' Output: GEEKSFORGEEKS Input: string =' My name is ayush' Output: MY NAME IS AYUSH 

Errors and Exceptions

  1. It takes no arguments, so it returns an error if a parameter is passed.
  2. Returned digits and the characters are returned as is. After conversion to uppercase, only the lowercase letter is returned.

Output:

 GEEKSFORGEEKS MY NAME IS AYUSH 

Usage: For a given row in python count count in uppercase letters, lowercase letters and spaces in a line and switch the case of the given string (convert lowercase letters to uppercase and vice versa).

Examples :

 Input: string = 'Python.Engineering is a computer Science portal for Geeks' Output: Uppercase - 4 Lowercase - 41 spaces - 7 gEEKSFORGEEKS IS A COMPUTER sCIENCE PORTAL FOR gEEKS Input: string =' My name is Ayush' Output: Uppercase - 2 Lowercase - 11 spaces - 3 mY NAME IS aYUSH 

Algorithm
1. Go through the given line character by character to its length, check if the character is lowercase or uppercase using built-in methods. 
2. If lower case, increment its corresponding counter, convert it to upper case using the upper () function, and add it on a new line, if upper case, increment its corresponding counter, convert it to lower case using the lower () function, and add it on a new line. 
3. If there is a space, increase its corresponding counter and add it on a new line.
4. Type a new line.

# Python code to implement upper ()

 
# checking capital letters

string = 'pythonengineering'

print (string.upper ())

 

string = 'My name is ayush'

print (string.upper ())

Output:

 In original String: Uppercase - 4 Lowercase - 41 Spaces - 7 After changing cases: gEEKSFORgEEKS IS A COMPUTER sCIENCE PORTAL FOR gEEKS 




isupper (), islower (), lower (), upper () in Python and their applications: StackOverflow Questions

Answer #1

itertools.groupby is a tool for grouping items.

From the docs, we glean further what it might do:

# [k for k, g in groupby("AAAABBBCCDAABBB")] --> A B C D A B

# [list(g) for k, g in groupby("AAAABBBCCD")] --> AAAA BBB CC D

groupby objects yield key-group pairs where the group is a generator.

Features

  • A. Group consecutive items together
  • B. Group all occurrences of an item, given a sorted iterable
  • C. Specify how to group items with a key function *

Comparisons

# Define a printer for comparing outputs
>>> def print_groupby(iterable, keyfunc=None):
...    for k, g in it.groupby(iterable, keyfunc):
...        print("key: "{}"--> group: {}".format(k, list(g)))
# Feature A: group consecutive occurrences
>>> print_groupby("BCAACACAADBBB")
key: "B"--> group: ["B"]
key: "C"--> group: ["C"]
key: "A"--> group: ["A", "A"]
key: "C"--> group: ["C"]
key: "A"--> group: ["A"]
key: "C"--> group: ["C"]
key: "A"--> group: ["A", "A"]
key: "D"--> group: ["D"]
key: "B"--> group: ["B", "B", "B"]

# Feature B: group all occurrences
>>> print_groupby(sorted("BCAACACAADBBB"))
key: "A"--> group: ["A", "A", "A", "A", "A"]
key: "B"--> group: ["B", "B", "B", "B"]
key: "C"--> group: ["C", "C", "C"]
key: "D"--> group: ["D"]

# Feature C: group by a key function
>>> # islower = lambda s: s.islower()                      # equivalent
>>> def islower(s):
...     """Return True if a string is lowercase, else False."""   
...     return s.islower()
>>> print_groupby(sorted("bCAaCacAADBbB"), keyfunc=islower)
key: "False"--> group: ["A", "A", "A", "B", "B", "C", "C", "D"]
key: "True"--> group: ["a", "a", "b", "b", "c"]

Uses

Note: Several of the latter examples derive from Víctor Terrón"s PyCon (talk) (Spanish), "Kung Fu at Dawn with Itertools". See also the groupby source code written in C.

* A function where all items are passed through and compared, influencing the result. Other objects with key functions include sorted(), max() and min().


Response

# OP: Yes, you can use `groupby`, e.g. 
[do_something(list(g)) for _, g in groupby(lxml_elements, criteria_func)]

isupper (), islower (), lower (), upper () in Python and their applications: StackOverflow Questions

Answer #1

The simplest way to accomplish this is to put the input method in a while loop. Use continue when you get bad input, and break out of the loop when you"re satisfied.

When Your Input Might Raise an Exception

Use try and except to detect when the user enters data that can"t be parsed.

while True:
    try:
        # Note: Python 2.x users should use raw_input, the equivalent of 3.x"s input
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn"t understand that.")
        #better try again... Return to the start of the loop
        continue
    else:
        #age was successfully parsed!
        #we"re ready to exit the loop.
        break
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Implementing Your Own Validation Rules

If you want to reject values that Python can successfully parse, you can add your own validation logic.

while True:
    data = input("Please enter a loud message (must be all caps): ")
    if not data.isupper():
        print("Sorry, your response was not loud enough.")
        continue
    else:
        #we"re happy with the value given.
        #we"re ready to exit the loop.
        break

while True:
    data = input("Pick an answer from A to D:")
    if data.lower() not in ("a", "b", "c", "d"):
        print("Not an appropriate choice.")
    else:
        break

Combining Exception Handling and Custom Validation

Both of the above techniques can be combined into one loop.

while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, I didn"t understand that.")
        continue

    if age < 0:
        print("Sorry, your response must not be negative.")
        continue
    else:
        #age was successfully parsed, and we"re happy with its value.
        #we"re ready to exit the loop.
        break
if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

Encapsulating it All in a Function

If you need to ask your user for a lot of different values, it might be useful to put this code in a function, so you don"t have to retype it every time.

def get_non_negative_int(prompt):
    while True:
        try:
            value = int(input(prompt))
        except ValueError:
            print("Sorry, I didn"t understand that.")
            continue

        if value < 0:
            print("Sorry, your response must not be negative.")
            continue
        else:
            break
    return value

age = get_non_negative_int("Please enter your age: ")
kids = get_non_negative_int("Please enter the number of children you have: ")
salary = get_non_negative_int("Please enter your yearly earnings, in dollars: ")

Putting It All Together

You can extend this idea to make a very generic input function:

def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None):
    if min_ is not None and max_ is not None and max_ < min_:
        raise ValueError("min_ must be less than or equal to max_.")
    while True:
        ui = input(prompt)
        if type_ is not None:
            try:
                ui = type_(ui)
            except ValueError:
                print("Input type must be {0}.".format(type_.__name__))
                continue
        if max_ is not None and ui > max_:
            print("Input must be less than or equal to {0}.".format(max_))
        elif min_ is not None and ui < min_:
            print("Input must be greater than or equal to {0}.".format(min_))
        elif range_ is not None and ui not in range_:
            if isinstance(range_, range):
                template = "Input must be between {0.start} and {0.stop}."
                print(template.format(range_))
            else:
                template = "Input must be {0}."
                if len(range_) == 1:
                    print(template.format(*range_))
                else:
                    expected = " or ".join((
                        ", ".join(str(x) for x in range_[:-1]),
                        str(range_[-1])
                    ))
                    print(template.format(expected))
        else:
            return ui

With usage such as:

age = sanitised_input("Enter your age: ", int, 1, 101)
answer = sanitised_input("Enter your answer: ", str.lower, range_=("a", "b", "c", "d"))

Common Pitfalls, and Why you Should Avoid Them

The Redundant Use of Redundant input Statements

This method works but is generally considered poor style:

data = input("Please enter a loud message (must be all caps): ")
while not data.isupper():
    print("Sorry, your response was not loud enough.")
    data = input("Please enter a loud message (must be all caps): ")

It might look attractive initially because it"s shorter than the while True method, but it violates the Don"t Repeat Yourself principle of software development. This increases the likelihood of bugs in your system. What if you want to backport to 2.7 by changing input to raw_input, but accidentally change only the first input above? It"s a SyntaxError just waiting to happen.

Recursion Will Blow Your Stack

If you"ve just learned about recursion, you might be tempted to use it in get_non_negative_int so you can dispose of the while loop.

def get_non_negative_int(prompt):
    try:
        value = int(input(prompt))
    except ValueError:
        print("Sorry, I didn"t understand that.")
        return get_non_negative_int(prompt)

    if value < 0:
        print("Sorry, your response must not be negative.")
        return get_non_negative_int(prompt)
    else:
        return value

This appears to work fine most of the time, but if the user enters invalid data enough times, the script will terminate with a RuntimeError: maximum recursion depth exceeded. You may think "no fool would make 1000 mistakes in a row", but you"re underestimating the ingenuity of fools!

Get Solution for free from DataCamp guru

# Python- code to implement upper ()
# Specified line and newline

 

string = 'Python.Engineering is a computer Science portal for Geeks'

newstring = ''

count1 = 0

count2 = 0

count3 = 0

  

for a in string:

# Check lowercase letters and convert to uppercase.

if (a.isupper ()) = = True :

count1 + = 1

newstring + = (a.lower ())

# Check capital letters and convert to lowercase.

elif (a.islower ()) = = True :

count2 + = 1

newstring + = (a.upper ())

# Check for missing letters and add them on a new line as is.

elif (a.isspace ()) = = True :

count3 + = 1

  newstring + = a

print ( "In original String:" )

print ( " Uppercase - " , count1)

print ( "Lowercase -" , count2)

print ( "Spaces -" , count3)

 

print ( "After changing cases:" )

print (newstring)