Python Python Collections (2016, retired 2019) Slices sillyCase

I was playing in the REPL with this function and can't figure out why word2 returns an empty string after join method?

Basically as I stated. In the REPL word1 joins into 'str' just like i was hoping, but word2 returns "". If it's the same logic what is causing this?

sillycase.py
def sillycase(string):
    string = list(string)
    half = int(len(string)) // 2
    word1 = string[:half]
    word1 = "".join(word1[:half]).lower()
    word2 = string[half:]
    word2 = "".join(word2[half:]).upper()
    return word1 + word2

2 Answers

Steven Parker
Steven Parker
171,169 Points

You don't need the join, but what's happening here would be the same with or without it.

When "word2" is first assigned, it gets "half" of the iterable: "word2 = string[half:]"

Then, on the next line, the "join" starts with taking another slice: "word2[half:]"

But if the first slice made it only "half" long, then another slice that has a start value of "half" would not have any content.

HA that makes total sense now! I updated the code to:

word1 = "".join(word1).lower()

and

word 2 = "".join(word2).upper()

Now its perfect. Thank you for helping me understand why it had no content.

Kars Jansens
Kars Jansens
4,370 Points

I don't kwow why you should use "join". You can do this:

def sillycase(string):
    half = int(len(string)) // 2
    word1 = string[:half].lower()
    word2 = string[half:].upper()
    return word1 + word2

I was originally using concepts taught in the video.

Basically I was using join because I turned string into a list and had to turn it back.

Your code is how I passed the challenge, I was just trying to understand why word 2 returned and empty string with the same logic.