将片段分配给字符串

2024-10-17 06:14:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我四处寻找这个问题的答案/解决方案已经有一段时间了,因为似乎应该已经问过了。但是我没有找到任何关于重新分配slice的信息。我正在为在线代码教师树屋做一个小测验,他们给了我这个问题/作业:

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, //.

我已经从别人的问题中解脱出来,走了这么远:

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

我不知道为什么会错,但是当我以"Treehouse"为例运行它时,它返回"Treehouse"。如果还不清楚,我的问题是如何将string的前半部分小写,后半部分大写。你知道吗


Tags: andthetostringreturnexamplefunctionbe
3条回答

字符串的方法.lower().upper()返回一个新字符串,并且不起作用。下面的操作将直接添加由lowerupper返回的新字符串:

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

sillycase('treehouse')   # 'treeHOUSE'

您需要将.lower().upper()分配给变量,例如:

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

或者在你的情况下:

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

字符串是不可变的!当你这么做的时候

begining.lower()
end.upper()

beginingend没有改变,它们只是分别返回小写和大写字符串。所以为了得到你期望的结果,你可以这样做

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

相关问题 更多 >