Day 63: Indexing And Slicing

# Indexing
# note: sets can't be indexed

my_guitars = ["Gibson Les Paul", "Ibanez RG", "Fender Stratocaster"]

print(my_guitars[0])                # Gibson Les Paul

# Python allows negative indexing. -1 returns the last item aso
print(my_guitars[-1])               # Fender Stratocaster
print(my_guitars[-2])               # Ibanez RG


# indexing a tuple
print(("Marshall", "Laney", "Orange")[1])       # Laney

# indexing a string
print("Wampler"[3])                 # p - index starts at 0

# slicing
print(my_guitars[0:2])              # ['Gibson Les Paul', 'Ibanez RG']


# note: the first index is optional. negative indexing works here as well
print(my_guitars[:2])              # ['Gibson Les Paul', 'Ibanez RG']
print(my_guitars[:-1])              # ['Gibson Les Paul', 'Ibanez RG']


#Examples

# get first and last letter
name = "Robert"

print(name[0])                      # R
print(name[-1])                     # t

# delete the file extension
filename = "document.txt"

print(filename[0:-4])               # document

Eine Antwort auf „Day 63: Indexing And Slicing“

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.