Reputation: 1
I have just started to learn python. I got this statement:
output= " name: abc"
log =output.split("=")[1]
What does the [1]
denote? Why is it used?
Upvotes: 0
Views: 1155
Reputation: 1277
this is useful when you know for sure the string has the (=) equal-to symbol or the any character that you are splitting with. so that it splits the string and returns the list.
and then from the list you can choose which part of string is useful for you
in your case it will return IndexError since it is not returning a list.
output= " name= abc"
log =output.split("=")[1]
in this case this will be useful
Upvotes: 0
Reputation: 1121584
The [1]
is indexing into the list returned by output.split("=")
; if that method returns a list of 2 or more elements, the [1]
indexes the second element.
In your specific case, it'll raise an IndexError
, as there is no =
in output
. Because of this, the output.split("=")
method returns just a list with just one string.
You can try things like these in a Python interpreter prompt:
>>> output= " name: abc"
>>> output.split('=')
[' name: abc']
>>> output.split('=')[0]
' name: abc'
>>> output.split('=')[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Had you split on :
instead you'd have gotten a more useful result:
>>> output.split(':')[1]
' abc'
Upvotes: 6
Reputation: 32189
This is what the statement means:
output= " name: abc"
log =output.split("=")[1]
Take the string output
and split it on '='
and then get the second element in the resulting list (index 1)
However, you can see that your output
doesn't really contain any =
, you probably want:
output= "name=abc"
Here is the breakdown:
a = output.split('=')
>>> a
['name', 'abc']
>>> a[1]
abc
Upvotes: 3