HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Split string in half and change case accordingly

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
casehalfchangeaccordinglysplitandstring

Problem

I found the following challenge online:

Create a function that takes a string and returns that string with the first half lowercased and the last half uppercased.

eg: foobar == fooBAR

If it is an odd number then 'round' it up to find which letters to uppercase.

That sounded easy enough but I found the last requirement a little tricky. Eventually this is what I came up with:


def sillycase(silly):
    length=len(silly)
    firstHalf = silly[:length / 2 + (length % 2)].lower()
    secondHalf = silly[length / 2 + (length % 2):].upper()
    return firstHalf + secondHalf


but that seems repetitive and inefficient.

What could I have done to make it slicker, without sacrificing readability? I was actually a little surprised python didn't have a built in method to split a string in half.

Solution

Midpoint math is often a pain in the whatnot, but a real trick is to add 1 to the length before halving it. Additionally, instead of repeating the math multiple times, you can do it just once.

def sillycase(silly):
    mid=(len(silly) + 1) / 2
    firstHalf = silly[:mid].lower()
    secondHalf = silly[mid:].upper()
    return firstHalf + secondHalf


At that point, it becomes small enough to not need the temp variables:

def sillycase(silly):
    mid = (len(silly) + 1) // 2
    return silly[:mid].lower() + silly[mid:].upper() 

print (sillycase("hello"))
print (sillycase("helloa"))
print (sillycase("helloab"))


http://ideone.com/CqUdl5

Note the use of the integer divide which is suitable for both python 2.x and 3.

Code Snippets

def sillycase(silly):
    mid=(len(silly) + 1) / 2
    firstHalf = silly[:mid].lower()
    secondHalf = silly[mid:].upper()
    return firstHalf + secondHalf
def sillycase(silly):
    mid = (len(silly) + 1) // 2
    return silly[:mid].lower() + silly[mid:].upper() 

print (sillycase("hello"))
print (sillycase("helloa"))
print (sillycase("helloab"))

Context

StackExchange Code Review Q#86933, answer score: 15

Revisions (0)

No revisions yet.