Python中endswith使用例子
时间: 2023-05-23 17:05:28 浏览: 65
A:
endswith()方法是Python字符串的一个内置方法,它用于检查字符串是否以指定后缀结尾,返回值是True或False。以下是使用endswith()方法的例子:
1. 检查字符串是否以某个后缀结尾,返回True或False。
```python
s = 'hello world'
print(s.endswith('world')) # True
print(s.endswith('lo')) # False
```
2. 如果字符串以指定后缀结尾,执行相应操作。
```python
filename = 'example.txt'
if filename.endswith('.txt'):
print('This is a text file')
else:
print('This is not a text file')
```
3. 检查多个字符串是否以指定后缀('es')结尾。
```python
words = ['dogs', 'cats', 'houses', 'trees']
for word in words:
if word.endswith('es'):
print(word)
```
以上是Python中endswith的使用例子。注意,endswith()方法还可以接受可选参数start和end,用于指定字符串的开始和结束位置。
相关问题
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`。最后一个示例中,我们还指定了开始和结束位置来限制搜索范围。
python endswith例子
在Python中,`endswith()`方法可以用来判断字符串是否以指定的后缀结尾。下面是一个`endswith()`方法的例子:
```python
string = "Hello World"
print(string.endswith("ld"))
```
输出结果为:
```
True
```
在这个例子中,`endswith()`方法判断字符串"Hello World"是否以"ld"结尾,最后输出结果为True。