编程实现字符串切片,如对字符串"hello,python!hello,c!": ① 输出子串:'python' ② 用逆向切片输出子串:'hello,c' ③ 输出第一位至倒数第三位的字符 ④ 做成员测试,分别判定字符串'java'和'python'是否是其成员
时间: 2024-10-18 12:24:13 浏览: 38
Python实现输出字符串的所有子串,并按照长度排序
5星 · 资源好评率100%
在Python中,可以使用索引来实现字符串切片。下面是针对提供的例子"hello,python!hello,c!"的四种操作:
1. **输出子串 'python'**:
```python
str = "hello,python!hello,c!"
sub_str = str[7:14] # 索引从0开始,所以7到13对应的字符就是'python'
print(sub_str)
```
2. **用逆向切片输出子串 'hello,c'**:
```python
sub_str_reversed = str[-16:-9] # 从最后一个字符开始计数,直到倒数第二个'!'
print(sub_str_reversed)
```
3. **输出第一位至倒数第三位的字符**:
```python
sliced_chars = str[:13] # 切除倒数第三个字符('!')
print(sliced_chars)
```
4. **做成员测试判断 'java' 和 'python' 是否是原字符串成员**:
```python
if 'java' in str:
print(f"'java' is a member of the string.")
else:
print("'java' is not a member of the string.")
if 'python' in str:
print(f"'python' is a member of the string.")
else:
print("'python' is not a member of the string.")
```
阅读全文