python 判断字符串是否以什么结尾
时间: 2025-03-11 08:20:15 浏览: 69
### 如何在 Python 中检查字符串是否以特定字符结尾
在 Python 中,可以使用 `str.endswith()` 方法来判断一个字符串是否以指定的字符或子串结尾。此方法返回布尔值 True 或 False 表示匹配结果。
`str.endswith(suffix[, start[, end]])` 的参数说明如下:
- suffix:可以是一个字符串或是多个用于比较的元组。
- start 和 end 参数是可选的,用来指定搜索范围[^2]。
下面给出一段简单的代码演示如何应用该函数:
```python
def check_string_ends_with(s, target_char):
"""Check if the string ends with a specific character."""
return s.endswith(target_char)
test_str = "hello world"
target_char = 'd'
result = check_string_ends_with(test_str, target_char)
print(f"'{test_str}' 是否以 '{target_char}' 结尾:", result)
```
当执行上述程序时,如果测试字符串确实是以目标字符结束,则会输出相应的确认信息;反之则不会[^4]。
对于更复杂的场景,比如想要验证文件名是否具有某种扩展名,也可以利用这个特性来进行处理:
```python
filename = "example.txt"
extension = ".txt"
if filename.endswith(extension):
print("这是一个文本文件")
else:
print("这不是一个文本文件")
```
阅读全文
相关推荐



















