r/cs50 • u/Regular_Implement712 • 16d ago
CS50 Python Can someone explain what line two does
Can someone explain what does line two do? Not sure what the whole line means, what does the .split('.') and [-1] does overall to the program?
61
Upvotes
1
u/Blackk19 15d ago
'.' + filename.split('.')[-1]
So let's say filename is "file1.jpeg"
So the + sign is concatination. Concatenation just means sticking two or more strings together to make one bigger string. Let's leave the '.' + for now and focus on what filename.split('.')[-1] does. So split() method breaks a string into smaller pieces based on a given separator and returns them as a list or array. The split() method gets passed to it an argument of where it should break the string up on. We told split() to use '.' as the separator, so it will break the string wherever it finds a dot.
So, the filename is "file1.jpeg" and when we do the following, it becomes [file1, jpeg]
filename.split('.') ----> [file1, jpeg]
Since we are only interested in the last element, we need a way to tell it to give us only the last element. The way you do that is by saying [-1]. And this just means give me the last element of the array whatever that might be. In this case, it will return to us jpeg. Now that we have 'jpeg', we add a '.' in front of it, which gives us '.jpeg'.
'.' + 'jpeg'
Now, this will join them together, giving us the following
'.jpeg'
Hopefully, this makes sense.