Indeksering og Slicing
123s = "python" print(s[0]) # 'p' (first character) print(s[5]) # 'n' (sixth character)
123s = "python" print(s[-1]) # 'n' (last character) print(s[-2]) # 'o' (second from the end)
12s = "python" print(s[10]) # IndexError: string index out of range
12s = "python" s[0] = 'P' # TypeError: 'str' object does not support item assignment
12345s = "python" print(s[1:4]) # 'yth' (indices 1,2,3) print(s[:4]) # 'pyth' (start defaults to 0) print(s[3:]) # 'hon' (stop defaults to len(s)) print(s[::2]) # 'pto' (every 2nd character)
12s = "python" print(s[0:100]) # 'python'
123s = "python" print(s[-3:]) # 'hon' (last three) print(s[::-1]) # 'nohtyp' (reverse)
Note
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 2
Spør AI
Spør AI
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår
Fantastisk!
Completion rate forbedret til 3.45
Indeksering og Slicing
Sveip for å vise menyen
123s = "python" print(s[0]) # 'p' (first character) print(s[5]) # 'n' (sixth character)
123s = "python" print(s[-1]) # 'n' (last character) print(s[-2]) # 'o' (second from the end)
12s = "python" print(s[10]) # IndexError: string index out of range
12s = "python" s[0] = 'P' # TypeError: 'str' object does not support item assignment
12345s = "python" print(s[1:4]) # 'yth' (indices 1,2,3) print(s[:4]) # 'pyth' (start defaults to 0) print(s[3:]) # 'hon' (stop defaults to len(s)) print(s[::2]) # 'pto' (every 2nd character)
12s = "python" print(s[0:100]) # 'python'
123s = "python" print(s[-3:]) # 'hon' (last three) print(s[::-1]) # 'nohtyp' (reverse)
Note
Alt var klart?
Takk for tilbakemeldingene dine!
Seksjon 3. Kapittel 2