在循环列表后删除空白



所以,我试着从几个变量中剥离,我知道他们之前没有空格到返回语句,所以我试着在return语句中剥离变量,但空白仍然存在…

我确定这很简单,或者也许重写循环是最好的?

def main():
file = input("File name:")
extension(file)

def extension(s):
split = (s.split("."))
join_s = (''.join(split[1]))
image_e = ['jpg', 'gif', 'jpeg', 'png']
for i in image_e:
print(image_e)
if join_s in image_e:
return print("Image/", join_s)
else:
return print("Application/", join_s)

main()

输出如下所示:

Image/ jpg

编辑:其中一个评论问我为什么使用return,因为如果我只使用print,它会显示3-4次不同的打印时间,在这种情况下我为什么不应该使用return,或者为什么它会连续显示4次?(假设是因为循环)

看起来您想要生成一个内容类型字符串。可以这样做:

import os
def extension(s):
ext = s.rsplit('.')[1]  # split on the *last* period
if ext in ('jpg', 'gif', 'jpeg', 'png'):
return f'Image/{ext}'
else:
return f'Application/{ext}'
file = input('File name: ')
content_type = extension(file)
print(content_type)

输出:

File name: test.jpg
Image/jpg

看起来您想从给定的文件名中确定mime类型。

import mimetypes
filename = "somefilename.png"
guessed_type, encoding = mimetypes.guess_type(filename)

guessed_type:

图像/png

Python通过标准库提供了许多特性/函数。

这里有一些其他的方法:

os

import os
​
filename = "somefilename.png"
base, ext = os.path.splitext(filename)

(somefilename, . png)

pathlib

from pathlib import Path
filename = "somefilename.png"
f = Path(filename)
f.suffix

. png">

对于字符串,python有.startswith().endswith()方法,它们可以选择接受一个可迭代对象,因此您可以在不拆分字符串的情况下编写此代码:

filename = "somefilename.png"
image_exts = ('jpg', 'gif', 'jpeg', 'png')
if filename.endswith(image_exts):
ext = filename.split(".")[-1]
print(f"Image/{ext}")