w3resource

Python: Convert a string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters


Uppercase string if 2+ uppercase chars in first 4.

Write a Python function to convert a given string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters.

Python String Exercises: Convert a string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters

Sample Solution:

Python Code:

# Define a function named to_uppercase that takes one argument, 'str1'.
def to_uppercase(str1):
    # Initialize a variable 'num_upper' to count the uppercase letters in the first 4 characters of 'str1'.
    num_upper = 0

    # Iterate through the first 4 characters of 'str1'.
    for letter in str1[:4]:
        # Check if the uppercase version of the letter is the same as the original letter.
        if letter.upper() == letter:
            # If they are the same, increment the 'num_upper' count.
            num_upper += 1

    # Check if the count of uppercase letters is greater than or equal to 2.
    if num_upper >= 2:
        # If there are 2 or more uppercase letters in the first 4 characters, return 'str1' in all uppercase.
        return str1.upper()
    
    # If there are fewer than 2 uppercase letters in the first 4 characters, return 'str1' as it is.
    return str1

# Call the to_uppercase function with different input strings and print the results.
print(to_uppercase('Python'))  # Output: 'Python' (Not all uppercase)
print(to_uppercase('PyThon'))  # Output: 'PYTHON' (All uppercase) 

Sample Output:

Python                                                                                                        
PYTHON

Flowchart:

Flowchart: Convert a string to all uppercase if it contains at least 2 uppercase characters in the first 4 characters

For more Practice: Solve these Related Problems:

  • Write a Python function to convert an entire string to uppercase if it contains at least two uppercase characters in its first four characters.
  • Write a Python program to check the first four characters for uppercase letters and conditionally convert the string.
  • Write a Python program to iterate over the first four characters, count uppercase letters, and then apply str.upper() if condition is met.
  • Write a Python program to use a combination of slicing and sum() on boolean expressions to determine if the string should be uppercased.

Go to:


Previous: Write a Python function to reverse a string if it's length is a multiple of 4.
Next: Write a Python program to sort a string lexicographically.

Python Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.