str = "Hello,Python"; suffix = "Python"; print (str.endswith(suffix,2));
时间: 2024-06-07 19:08:30 浏览: 10
输出结果为 False。
这是因为 `str.endswith(suffix,2)` 表示从字符串 `str` 的第2个位置开始往后匹配后缀字符串 `suffix`,而在本例中,第2个位置是字符 'l',而后缀字符串 "Python" 并不匹配,因此返回 False。如果修改为 `str.endswith(suffix,7)`,则表示从字符串 `str` 的第7个位置开始往后匹配后缀字符串 `suffix`,此时返回 True。
相关问题
python .endswith
`str.endswith(suffix[, start[, end]])` 是 Python 字符串内置方法,用于检查字符串是否以指定的后缀结尾。
- `suffix`:要检查的后缀,可以是一个字符串或者是一个元组(以元组形式提供多个后缀)。
- `start`(可选):搜索的起始位置,默认为 0,表示从字符串的开头开始搜索。
- `end`(可选):搜索的结束位置,默认为字符串的长度,表示在整个字符串范围内搜索。
该方法返回一个布尔值,如果字符串以指定后缀结尾,则返回 `True`,否则返回 `False`。
以下是使用示例:
```python
text = "Hello, world!"
print(text.endswith("world!")) # True
print(text.endswith("world")) # False
print(text.endswith(("!", "?"))) # True
print(text.endswith(("!", "?"), 0, 12)) # False
```
以上代码中,第一个 `endswith` 示例检查字符串 `text` 是否以 "world!" 结尾,返回 `True`。第二个示例检查字符串是否以 "world" 结尾,返回 `False`。
第三个示例中,我们使用元组作为后缀参数,检查字符串是否以 "!" 或 "?" 结尾,返回 `True`。最后一个示例中,我们还指定了开始和结束位置来限制搜索范围。
str.endswith()用法
`str.endswith()`是一个字符串方法,用于判断一个字符串是否以指定的后缀结尾。它的语法如下:
```
str.endswith(suffix[, start[, end]])
```
其中,`suffix`是要检查的后缀字符串,`start`和`end`是可选参数,用于指定要检查的字符串的起始和结束位置。如果不指定这两个参数,`str.endswith()`将在整个字符串中搜索后缀。
`str.endswith()`方法返回一个布尔值,如果字符串以指定的后缀结尾则返回`True`,否则返回`False`。
以下是一些示例:
```python
s = 'hello world'
print(s.endswith('world')) # True
print(s.endswith('world', 0, 5)) # False
print(s.endswith(('world', 'Python'))) # True,因为'world'是后缀中的一个
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)