Python string comparison failing
Question:
small Python prog’ to sort downloads folder by matching the extension,
I am getting a False (it seems to me) string match in the following.
I searched but seemed to only find issues regarding REGEX matching, or more complex stuff!
seperate the extension
for filename in os.listdir(src_base_folder):
orig_title, orig_ext = os.path.splitext(filename)
make lower case for ease of matching and strip the leading "."
I suspect my issue is here somehow..
extension = str.lower(orig_ext)[1:]
The test below is working fine for everything except "S22F350FH.icm",
a colorscheme file for setting up a monitor.
I print out the "extension" which shows as "icm" yet I am getting a FALSE match
in this code against the extensions for various image types:
if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp":
Appreciate your thoughts.
Answers:
Instead of if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp"
, you should use:
if extension in ["jpg", "jpeg", "png", "gif", "bmp"]:
The interpreter treats conditionals as follows:
if expr_1 or expr_2 or expr_3:
More concisely,
if (expr_1) or (expr_2) or (expr_3)
Evaluating your program, the interpreter treats if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp"
as:
if (extension == "jpg") or ("jpeg") or ("png") or ("gif") or ("bmp"):
Since non-empty strings are truthy, this will always evaluate to True
. Instead, use what @Mayank suggested, if extension in ["jpg", "jpeg", "png", "gif", "bmp"]:
.
small Python prog’ to sort downloads folder by matching the extension,
I am getting a False (it seems to me) string match in the following.
I searched but seemed to only find issues regarding REGEX matching, or more complex stuff!
seperate the extension
for filename in os.listdir(src_base_folder):
orig_title, orig_ext = os.path.splitext(filename)
make lower case for ease of matching and strip the leading "."
I suspect my issue is here somehow..
extension = str.lower(orig_ext)[1:]
The test below is working fine for everything except "S22F350FH.icm",
a colorscheme file for setting up a monitor.
I print out the "extension" which shows as "icm" yet I am getting a FALSE match
in this code against the extensions for various image types:
if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp":
Appreciate your thoughts.
Instead of if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp"
, you should use:
if extension in ["jpg", "jpeg", "png", "gif", "bmp"]:
The interpreter treats conditionals as follows:
if expr_1 or expr_2 or expr_3:
More concisely,
if (expr_1) or (expr_2) or (expr_3)
Evaluating your program, the interpreter treats if extension == "jpg" or "jpeg" or "png" or "gif" or "bmp"
as:
if (extension == "jpg") or ("jpeg") or ("png") or ("gif") or ("bmp"):
Since non-empty strings are truthy, this will always evaluate to True
. Instead, use what @Mayank suggested, if extension in ["jpg", "jpeg", "png", "gif", "bmp"]:
.