A common design and function string back to the data structure of the given file name extension

Design a function to return to the given filename extension

def get_suffix(filename, has_dot=False):

 """
 获取文件名的后缀名

 :param filename:文件名
 :param has_dot:返回的后缀名是否需要带点
 :return:文件的后缀名
 """


 pos = filename.rfind('.')
 if 0 < pos < len(filename) - 1:
  index = pos if has_dot else pos + 1
  return filename[index:]
 else:
  return ''

test

print(get_suffix('aa'))
print(get_suffix('aa.txt'))
print(get_suffix('aa.py'))
print(get_suffix('aa.txt.py'))

Here Insert Picture Description

Published 96 original articles · won praise 8 · views 4338

Guess you like

Origin blog.csdn.net/weixin_46108954/article/details/104637432