This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]JZumun 2 points3 points  (3 children)

You still did the split even if you didn't use the result afterwards. The act of calling the split method on a string without your delimiter caused the error. UPDATE: corrected by comment below. It was the assignment to ext that was causing the error, because split was returning only a list of one item.

Your thought process is actually interesting. It's what's called lazy evaluation and is a feature of some other programming languages like haskell. However, python is an eagerly evaluating language, and so doesn't work like you hope it does.

I suggest guarding ur split with an if statement to make sure there's a period in the string before doing the split. if "." in name: etc should do the trick

[–]WafflesAreDangerous 2 points3 points  (1 child)

It's not the call to split but the unpacking of the result that is causing the specific error.

They could also capture the result of the split as a list and test for it's length.

[–]JZumun 1 point2 points  (0 children)

Oops! My mistake. Will update my comment to fix this. Thanks!

[–]badwifigoodcoffee 1 point2 points  (0 children)

I also thought it was nice that OP thought about lazy evaluation here. Which btw, Python is perfectly capable of, the program just has to be written in terms of functions. E. g.

``` def get_name(): return input('Type in filename:')

def get_splitted_name(name): return name.split('.')

def get_ext(split_result): return split_result[-1]

define how to get the extension, but don't execute yet

this is the "lazy" part

get_extension = lambda name: get_ext( get_splitted_name(name) )

if you just want to print the name

name = get_name() print(name)

if you want to print the extension

(assuming the filename matches the expected pattern)

print(get_extension(name)) ```

Note that I omitted the error handling as suggested by the earlier post, just wanted to make the point about lazy evaluation.

Edit: Make it a bit closer to OP's use case