简体   繁体   中英

How do I create a function using loops to return the number of upper case and lower case letters on python?

  • should use str.islower(), str.isupper(), str.istitle()

this is a rough code just to explain better. you can do that as you said:

def analyze(string): # define the function named analyze
    upper = 0
    lower = 0
    for i in string:
        if i.isupper():
            upper += 1
        if i.islower():
            lower += 1
     inupper = string.title()
     return lower, upper, inupper
analyze(input("something to input")) 
# if you want it in the function just put the input in the function.
print(analyze(input("something to input")))

in the question, it sounds like you wanted it on title case, though, you wanted to use "istitle()" that just indicates if it is a title case. this is my first answer so hopefully, it fits in StackOverflow.

I have implemented an example for you. I have added many comment to my code for the better understanding.

Code:

def converter(input_text):
    """
    Returns the number of upper case letters, lower case letters, as well as
    converting the string to Title Case.
    :param input_text: Text from the user.
    :return: number of upper case letters, lower case letters, Title Case string.
    """

    upper_case_counter = lower_case_counter = 0  # Define the counters

    for letter in input_text:  # Get the letters one-by-one
        if letter.isupper():  # True if the letter is upper case
            upper_case_counter += 1  # Increment the upper counter
            continue  # Get the next letter
        lower_case_counter += 1  # Increment the lower case counter (If the "if" statement is not True)

    return upper_case_counter, lower_case_counter, input_text.title()  # Return the upper, lower, title (In tuple type)


user_input = input("Please write your text: ")  # Get the input from user
upper, lower, title = converter(user_input)  # Unpacking the return value of "converter" function
print("Upper case letters number:{}\n"
      "Lower case letters number: {}\n"
      "Title text: {}".format(upper, lower, title))  # Print the result

If you have to use the x.islower() then your can do it like this:

for letter in input_text:  # Get the letters one-by-one
    if letter.isupper():  # True if the letter is upper case
        upper_case_counter += 1  # Increment the upper counter
    elif letter.islower():  # True if the letter is lower case
        lower_case_counter += 1  # Increment the lower case counter

Output:

>>> python3 test.py  
Please write your text: This is my TExt
Upper case letters number:3
Lower case letters number: 12
Title text: This Is My Text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM