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

stefano tartaglia
stefano tartaglia
4,302 Points

Better way of completing sillycase challenge

Challenge:

This one will be named sillycase and it'll take a single string as an argument.

sillycase should return the same string but the first half should be lowercased and the second half should be uppercased.

For example, with the string "Treehouse", sillycase would return "treeHOUSE".

def sillycase(string): half = int(len(string) /2 ) new_list = [] for x in list(string)[:half]: x = x.lower() new_list.append(x) for x in list(string)[half:]: x = x.upper() new_list.append(x) string = ''.join(new_list) print(string) return string

sillycase("hello") sillycase("treehoure")

I got the right answer i'm just wondering if there was a better way

1 Answer

Steven Parker
Steven Parker
231,269 Points

Here's a few ways to optimize the function:

  • you can use string concatenation to join strings directly instead of using a list as an intermediate
  • you could also apply the case conversions directly to the slices and save a few more steps
  • and the function doesn't need to "print" anything

When posting code, use the instructions for code formatting in the Markdown Cheatsheet pop-up below the "Add an Answer" area. :arrow_heading_down:   Or watch this video on code formatting.