检查字符串的开头或结尾。


二、解决方案

startswith()endswith()

filename = 'test.txt'
print(filename.endswith('.txt'))
print(filename.startswith('file.'))

输出:

True
False


检查多种匹配,将这些匹配放到一个元组中。

import os

filenames = os.listdir('.')     # 当前目录下的文件和文件夹
print(filenames)

输出:

['decision_tree_model.py', 
 'gbdt_classifier_example.py', 
 'gbdt_model.py', 
 'utils', 
 'test.txt'
 '__pycache__']

name_lst = [name for name in filenames if name.endswith(('.py', '.txt'))]
print(name_lst)
print()

输出:

['decision_tree_model.py', 
 'gbdt_classifier_example.py', 
 'gbdt_model.py', 
 'test.txt']


startswith()endswith()常与普通聚合函数结合使用。

print(any(name.endswith('.py') for name in filenames))

输出:

True


相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-28
  • 2022-01-30
  • 2021-11-23
  • 2021-09-16
  • 2022-12-23
猜你喜欢
  • 2022-01-03
  • 2022-12-23
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案