编写函数def niddle(string),如果string的长度为奇数就返回string中间位置上的字符,如果为偶数就返口中问位置上的两个字符。
时间: 2024-02-03 07:14:41 浏览: 23
以下是 Python 代码实现:
```python
def niddle(string):
length = len(string)
if length % 2 == 0:
return string[length // 2 - 1:length // 2 + 1]
else:
return string[length // 2]
```
函数中首先获取输入字符串的长度,如果长度为偶数,则返回中间两个字符,需要使用字符串切片。如果长度为奇数,则返回中间的一个字符。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)