Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将切片指定给字符串_Python_String_Slice - Fatal编程技术网

Python 将切片指定给字符串

Python 将切片指定给字符串,python,string,slice,Python,String,Slice,我四处寻找这个问题的答案/解决方案已经有一段时间了,因为它似乎应该已经被问过了。但是我没有找到任何关于重新分配切片的信息。我正在为在线代码教师树屋做一个测验,他们给了我这个问题/作业: 我需要你为我创建一个新函数。 这一个将被命名为sillycase,它将使用单个字符串作为参数。 sillycase应返回相同的字符串,但前半部分应小写,后半部分应大写。 例如,对于字符串“Treehouse”,sillycase将返回“Treehouse”。 不要担心四舍五入,但记住索引应该是 整数。您需要使用i

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

我需要你为我创建一个新函数。 这一个将被命名为sillycase,它将使用单个字符串作为参数。 sillycase应返回相同的字符串,但前半部分应小写,后半部分应大写。 例如,对于字符串“Treehouse”,sillycase将返回“Treehouse”。 不要担心四舍五入,但记住索引应该是 整数。您需要使用int()函数或整数除法,/.

我已经解决了其他人的问题,并且走到了这一步:

def sillycase(example):
    begining = example[:len(example) // 2]
    end = example[len(example) // 2:]
    begining.lower()
    end.upper()
    example = begining + end
    return example
我不确定为什么这是错误的,但当我以
“Treehouse”
为例运行它时,它返回
“Treehouse”
。如果还不清楚,我的问题是如何将
字符串的前半部分小写,后半部分大写。

字符串的方法
.lower()
.upper()
返回一个新字符串,但不起作用。以下操作可以直接添加由
lower
upper
返回的新字符串:

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()
begining
end
没有改变,它们只是分别返回小写和大写字符串。所以,为了得到你期望的结果,你可以这样做

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