Archive:Python/Operators: Difference between revisions

wikademia>ArrowStomper
wikademia>ArrowStomper
Line 70: Line 70:


==Indexing==
==Indexing==
You have already learned how to index in lesson 2.  When you typed x[3] you where indexing.  You may also index a string without first making a variable represent it. 
Type:
>>>'''"I Love Wikipedia"'''[5]
'''e'''
simple enough.
===Slicing===
''Slicing'' is used to access a range of elements the way that ''indexing'' accessess one element.
Type:
>>>'''x = "Wikipedia and Python are awesome"'''
Now Type:
>>>'''print x[14:32]
'''Python are awesome'''
The numbers that you enter after the variable (the [14:32]) are called ''indices''.  The way the last one works is hard to understand at first.  I'll do another example to make it clear.
Type:
>>>'''x = '1234''''
Now type:
'''print x[1:3]''''
'''23'''
It prints out the 2 because it starts numbering at 0, but the reason it prints out the 3 instead of the 4 is because it counts the '''[3]''' that you entered as the end point and does not include it.  Seems wierd at first but easy to get used to.
You may also use negative numbers as the indices '''(x[-12:-])'''.  If you only use one negative indice '''(x[-4:])''' Python will print starting with the element selected and go until the end of the string, tuple or list.  This works for positive indices as well '''(x[:3])'''.  Python will print the first 2 elements of '''x'''.
Another thing that you can do when ''splicing'' is enter the ''step'' indice.
Type:
>>>'''x = "0123456789"'''
Now Type:
>>>'''x[1:-1:3]'''
''' '147' '''
==