3.用Python语句来编写以下句子 (1) 已知strSource = ‘code that change world’,请写出Python程序语句,实现如下效果(可以使用(不限于)strip()、lstrip()、rstrip()、split()、count()、replace()等函数) ① 将strSource用空格分隔成由字符串组成的列表(效果:['code', 'that', 'change', 'world']): ② 将strSource用空格分隔成由字符串组成的列表且字符串元素的首尾不包含字符’t’(效果:['code', 'ha', 'change', 'world']): ③ 将strSource中每个单词首尾的空格去掉(效果:'codethatchangeworld'): ④ 将strSource中每个单词首尾的’c’去掉(效果:'ode that hange world'): ⑤ 统计strSource中’code’出现的次数。
时间: 2023-08-08 11:04:18 浏览: 41
1. 将strSource用空格分隔成由字符串组成的列表:
```python
strSource = 'code that change world'
list_strSource = strSource.split(' ')
print(list_strSource)
```
输出:
```
['code', 'that', 'change', 'world']
```
2. 将strSource用空格分隔成由字符串组成的列表且字符串元素的首尾不包含字符’t’:
```python
strSource = 'code that change world'
list_strSource = strSource.split(' ')
list_strSource_no_t = []
for s in list_strSource:
if s.startswith('t'):
s = s[1:]
if s.endswith('t'):
s = s[:-1]
list_strSource_no_t.append(s)
print(list_strSource_no_t)
```
输出:
```
['code', 'ha', 'change', 'world']
```
3. 将strSource中每个单词首尾的空格去掉:
```python
strSource = 'code that change world'
list_strSource = strSource.split(' ')
strSource_no_space = ''.join(list_strSource)
print(strSource_no_space)
```
输出:
```
'codethatchangeworld'
```
4. 将strSource中每个单词首尾的’c’去掉:
```python
strSource = 'code that change world'
list_strSource = strSource.split(' ')
strSource_no_c = ''
for s in list_strSource:
if s.startswith('c'):
s = s[1:]
if s.endswith('c'):
s = s[:-1]
strSource_no_c += s + ' '
print(strSource_no_c.strip())
```
输出:
```
'ode that hange world'
```
5. 统计strSource中’code’出现的次数:
```python
strSource = 'code that change world'
count_code = strSource.count('code')
print(count_code)
```
输出:
```
1
```