在python中用endswith函数举个简单的例子
时间: 2024-02-11 13:08:45 浏览: 29
当我们需要判断一个字符串是否以某个特定的子字符串结尾时,可以使用Python中的endswith()函数。举个简单的例子,假设我们有一个字符串s,我们想要判断它是否以字符串"world"结尾,可以使用以下代码:
```
s = "hello world"
if s.endswith("world"):
print("s ends with world")
else:
print("s does not end with world")
```
运行该代码,输出结果为:
```
s ends with world
```
这是因为字符串s以"world"结尾。
相关问题
python中endswith()函数
Python中endswith()函数是一个字符串方法,用于检查字符串是否以指定的后缀结尾。该函数接受一个参数suffix,表示要检查的后缀字符串。如果原字符串以suffix结尾,则返回True,否则返回False。该函数的语法如下:
str.endswith(suffix[, start[, end]])
其中,suffix表示要检查的后缀字符串,start和end表示可选的起始和结束位置。如果指定了start和end,则只在该范围内检查字符串是否以suffix结尾。如果不指定start和end,则默认在整个字符串中检查。
Python中endswith使用例子
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,用于指定字符串的开始和结束位置。