2.字符串切片和索引 str1 = "人生苦短,我用python" 1、逆序输出str1 2、输出str1的前4个字符 3、输出str1的后4个字符 4、间隔输出str1 5、输出months字符串里月份的首字母
时间: 2023-09-20 21:06:16 浏览: 161
### 回答1:
1. 逆序输出str1:
```python
str1 = "人生苦短,我用python"
print(str1[::-1])
```
输出结果为:
```
nohtypuy我,短苦生人
```
2. 输出str1的前4个字符:
```python
str1 = "人生苦短,我用python"
print(str1[:4])
```
输出结果为:
```
人生苦短
```
3. 输出str1的后4个字符:
```python
str1 = "人生苦短,我用python"
print(str1[-4:])
```
输出结果为:
```
ython
```
4. 间隔输出str1:
```python
str1 = "人生苦短,我用python"
print(str1[::2])
```
输出结果为:
```
人苦,用to
```
5. 输出months字符串里月份的首字母:
```python
months = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
month_list = months.split(',')
initials = [month[0] for month in month_list]
print(initials)
```
输出结果为:
```
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D']
```
### 回答2:
1、逆序输出str1:可以使用切片和步长的方式来逆序输出str1,代码如下:
```python
str1 = "人生苦短,我用python"
reverse_str = str1[::-1]
print(reverse_str)
```
输出结果为:`nohtyp用我,短苦生人`
2、输出str1的前4个字符:使用切片的方式来输出str1的前4个字符,代码如下:
```python
str1 = "人生苦短,我用python"
first_four = str1[:4]
print(first_four)
```
输出结果为:`人生苦短`
3、输出str1的后4个字符:同样使用切片的方式来输出str1的后4个字符,代码如下:
```python
str1 = "人生苦短,我用python"
last_four = str1[-4:]
print(last_four)
```
输出结果为:`用python`
4、间隔输出str1:可以使用步长的方式来实现间隔输出str1,代码如下:
```python
str1 = "人生苦短,我用python"
interval_str = str1[::2]
print(interval_str)
```
输出结果为:`人苦,用thn`
5、输出months字符串里月份的首字母:可以使用切片的方式来输出months字符串里月份的首字母,代码如下:
```python
months = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
first_letters = months[::4]
print(first_letters)
```
输出结果为:`J,F,M,A,M,J,J,A,S,O,N,D`
### 回答3:
1、逆序输出str1:
```python
str1 = "人生苦短,我用python"
reverse_str1 = str1[::-1]
print(reverse_str1)
```
输出结果为:`nohtyp用我,短苦生人`
2、输出str1的前4个字符:
```python
str1 = "人生苦短,我用python"
first_4_chars = str1[:4]
print(first_4_chars)
```
输出结果为:`人生苦短`
3、输出str1的后4个字符:
```python
str1 = "人生苦短,我用python"
last_4_chars = str1[-4:]
print(last_4_chars)
```
输出结果为:`用python`
4、间隔输出str1:
```python
str1 = "人生苦短,我用python"
interleaved_str = str1[::2]
print(interleaved_str)
```
输出结果为:`人苦,用tn`
5、输出months字符串里月份的首字母:
```python
months = "January, February, March, April, May"
first_letters = [month[0] for month in months.split(", ")]
print(first_letters)
```
输出结果为:`['J', 'F', 'M', 'A', 'M']`
阅读全文