简体   繁体   中英

assigning slices to strings

I've looked around for an answer/solution for this question for a bit, as it seems like it should have been asked already. But I have failed to find anything about reassigning a slice . I'm doing one of the quizzes for the online code teacher Treehouse, and they have given me this question/assignment:

I need you to create a new function for me. 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". Don't worry about rounding your halves, but remember that indexes should be integers. You'll want to use the int() function or integer division, //.

I've worked off of other people's questions and gotten this far:

def sillycase(example):
    begining = example[:len(example) // 2]
    end = example[len(example) // 2:]
    begining.lower()
    end.upper()
    example = begining + end
    return example

I'm not sure why that is wrong, but when I run it with example being "Treehouse" , it returns "Treehouse" . If not clear yet my question is how to get the first half of a string lowercased, and the second half uppercased.

The methods .lower() and .upper() for strings return a new string and don't work in-place. The following should work which adds the new strings returned by lower and upper directly:

def sillycase(example):
    beginning = example[:len(example) // 2]
    end = example[len(example) // 2:]
    example = beginning.lower() + end.upper()
    return example

sillycase('treehouse')   # 'treeHOUSE'

You need to assign .lower() and .upper() to the variables, for example:

begining = begining.lower()
end = end.upper()
example = begining + end

or in your case:

def sillycase(example):
    begining = example[:len(example) // 2].lower()
    end = example[len(example) // 2:].upper()
    example = begining + end
    return example

Strings are immutable! When you do

begining.lower()
end.upper()

begining and end are not changed , they just simply return you the lower and uppercase strings respectively. So in order to get the result you are expecting do something like this

begining = begining.lower()
end = end.upper()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM