python查找后缀 不区分大小写
时间: 2023-08-15 07:12:02 浏览: 87
你可以使用Python的字符串方法来查找后缀,而不区分大小写。可以使用`str.endswith()`方法配合字符串切片来实现。下面是一个示例代码:
```python
def find_suffix(filename, suffix):
return filename.lower().endswith(suffix.lower())
# 测试示例
filename = "example.txt"
suffix = ".TXT"
result = find_suffix(filename, suffix)
print(result) # 输出 True
```
在上面的代码中,我们定义了一个`find_suffix()`函数,它将文件名和后缀作为参数。函数内部首先使用`lower()`方法将文件名和后缀转换为小写字母,并使用`endswith()`方法检查文件名是否以指定后缀结尾。这样就可以实现不区分大小写的后缀查找。
注意:这种方法只适用于后缀是纯字母的情况。如果后缀中包含其他特殊字符,可能需要根据具体情况进行适当修改。
相关问题
python字符串查找不区分大小写
可以将字符串全部转换为小写或大写,然后再进行查找,这样就不区分大小写了。例如:
```python
string = "Hello World"
substring = "world"
if substring.lower() in string.lower():
print("Substring found")
else:
print("Substring not found")
```
输出结果为:Substring found。
python正则表达不区分大小写
是的,Python正则表达式默认是区分大小写的,但可以通过在正则表达式中添加标志来实现不区分大小写的匹配。具体来说,可以使用re.IGNORECASE或re.I标志来实现不区分大小写的匹配。例如,以下代码将匹配所有以"hello"开头的字符串,不论其大小写:
```python
import re
text = "Hello world!"
pattern = re.compile("^hello", re.IGNORECASE)
match = pattern.search(text)
if match:
print("Match found!")
else:
print("Match not found.")
```