How to Fix String Casing in Python

0 min read 180 words

The challenge

You will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on:

  • make as few changes as possible.
  • if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase.

For example:

solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase.
solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase.
solve("coDE") = "code". Upper == lowercase. Change all to lowercase.

The solution in Python code

Option 1:

def solve(s):
    lower = 0
    
    for c in list(s):
        if c.lower()==c:
            lower += 1
            
    return s.lower() if lower>=len(s)/2 else s.upper()

Option 2:

def solve(s):
    return (s.lower, s.upper)[sum(map(str.isupper, s)) > len(s) / 2]()

Option 3:

def solve(s):
    upper = 0
    lower = 0
    
    for char in s:
        if char.islower():
            lower += 1
        else:
            upper += 1
            
    if upper == lower or lower > upper:
        return s.lower()
    else:
        return s.upper()

Test cases to validate our solution

test.it("Basic tests")
test.assert_equals(solve("code"),"code")
test.assert_equals(solve("CODe"),"CODE")
test.assert_equals(solve("COde"),"code")
test.assert_equals(solve("Code"),"code")
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags

Recent Posts