Monday, 12 June 2017
What does [:-1] mean/do in python?
Answer
Answer
Working on a python assignment and was curious as to what [:-1] means in the context of the following code: instructions = f.readline()[:-1]
Have searched on here on S.O. and on Google but to no avail. Would love an explanation!
Answer
It slices the string to omit the last character, in this case a newline character:
>>> 'test\n'[:-1]
'test'
Since this works even on empty strings, it's a pretty safe way of removing that last character, if present:
>>> ''[:-1]
''
This works on any sequence, not just strings.
For lines in a text file, I’d actually use line.rstrip('\n')
to only remove a newline; sometimes the last line in the file doesn’t end in a newline character and using slicing then removes whatever other character is last on that line.
c++ - Does curly brackets matter for empty constructor?
Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...
-
A fair amount of the second act of The Dark Knight Rises has a class warfare plotline. This is foreshadowed in the trailers with Selina Ky...
-
I'm still trying to wrap my head around how the following expression results in undefined behavior: a = a++; Upon searching SO...
-
i have added this sql in my code , function devenir_client_dataforform() { $type = $_POST['clientType']; //$produit...
No comments:
Post a Comment