python中rfind()方法

题目:自己实现一个splitext()方法
import os
def my_splitext(path):
index = path.rfind(’.’)
start = path[:index]
end = path[index:]
return start,end
‘’’
以上方法有瑕疵, 当路径中不存在’.‘时效果不一致
原因为rfind方法如果没有匹配项,返回值为-1
‘’’
path = r’C:\Users\Administrator\Desktop\mima’
tp = my_splitext(path)
print(tp)
print(type(tp))
print(os.path.splitext(path))

‘’’
修改后,增加判定
‘’’
import os
def my_splitext(path):
if ‘.’ in path:
index = path.rfind(’.’)
start = path[:index]
end = path[index:]
else:
start = path
end = ‘’
return start,end
path = r’C:\Users\Administrator\Desktop\mima’
tp = my_splitext(path)
print(tp)
print(type(tp))
print(os.path.splitext(path))

你可能感兴趣的:(python之闲的蛋疼)