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

How does this code work?

Hello,

I am confused by how this code works (see below). I know it converts the second half of the string to uppercase. It is a little confusing, and I cannot get my head around it.

def sillycase(a):
    print(a[round(len(a) / 2):].upper())      
sillycase("Treehouse")  

Thanks.

2 Answers

Let's go from inside out.

a[round(len(a) / 2):]

This is string slicing. a[x:y] returns part (slice) of a string a starting from x index and ending on a y-1 index. Here we get a slice of a from round(len(a) / 2) index till the end of a sting.

a[round(len(a) / 2):].upper()

Then all the letters in the string slice are turned to upper case

print(a[round(len(a) / 2):].upper()) 

and printed

So when I divided by 2 it took the latter half of the string because I added : at the end of my code. How did it know which bit to take. Sorry I am still a little confused.

I would recommend you the "Python Collections" course, or at least this one lesson https://teamtreehouse.com/library/python-collections/slices/introduction-to-slices to get more familiar with slices