Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Slices sillyCase

Trevor Wood
Trevor Wood
17,828 Points

Can anyone compare their answer with mine, Python?

I'm pretty sure that this wasn't the way that the teacher wanted us to solve this. There must be an easier way to get this right.

silly.py
# The first half of the string, rounded with round(), should be lowercased.
# The second half should be uppercased.
import math

def sillycase(value):
  length = len(value)
  firsthalf = math.ceil(length/2)
  secondhalf = math.floor(length/2)

  if firsthalf > secondhalf:
    secondhalf = secondhalf+1

  firsttext = value[0:firsthalf]
  secondtext = value[secondhalf:]
  answer = firsttext.lower()+secondtext.upper()

  return answer


print(sillycase("frog")) #should return frOG
print(sillycase("trevor")) # treVOR
print(sillycase("kenneth")) # kennETH
print(sillycase("treehouse")) #treehOUSE

1 Answer

Frederik Andersen
Frederik Andersen
10,012 Points

This should be a little more easy :)

def sillycase(my_str):
  half_lenght = round(len(my_str) / 2)
  return my_str[0:half_lenght].lower() + my_str[half_lenght::].upper()

What im doing is: Getting the rounded number of half the lenght of the string. Thats because slices use integers not floats. Returning my_str from index0 to half of the string + my_str from half of the string to the end of the string.

Hope this helped :-)

Frederik

Hey Frederik,

Great answer.

Can you explain why int() would not also work in this case?

Frederik Andersen
Frederik Andersen
10,012 Points

Hi meagantan,

Not sure if I get your question.

Are thinking of int(my_str)?

If you are, its because my_str contains letters. int() will only work if the string is numbers only.

For example:

int("123")

This will raise an ValueError:

int("abc")
int("a1b2c3")

Hope this helps :) If not just specify a bit more and il try to answer!

Frederik