python endswith例子
时间: 2023-07-06 16:35:59 浏览: 36
在Python中,`endswith()`方法可以用来判断字符串是否以指定的后缀结尾。下面是一个`endswith()`方法的例子:
```python
string = "Hello World"
print(string.endswith("ld"))
```
输出结果为:
```
True
```
在这个例子中,`endswith()`方法判断字符串"Hello World"是否以"ld"结尾,最后输出结果为True。
相关问题
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,用于指定字符串的开始和结束位置。
在python中用endswith函数举个简单的例子
当我们需要判断一个字符串是否以某个特定的子字符串结尾时,可以使用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"结尾。