Sõne viilutamine

Sõnedest on võimalik saada üksikuid elemente [] operaatoriga ja alamsõnede jaoks on tähistus [start:stop:step].

Esimese tähe indeks on sõnes 0 ja viimane indeksil len(string) - 1.

  • [start] indeks, kust alustada tükeldamist, selle ärajätmisel eeldab Python, et tükeldamine algab algusest

  • [stop] elemendi indeks, kus peatuda, seda elementi ei arvata vahemikku, ärajätmisel tükeldatakse lõpuni

  • [step] sammu suurus itereerimisel, vaikimisi on see 1 ning -1 itereerib elemendid tagurpidi

# no pec str1 = "Python String" # Single character with slice notation, element at index 3 is excluded. print(str1[2:3]) # -> t # Notation for getting a single character. print(str1[2]) # -> t # Use negative numbers to get characters from the end. print(str1[-1]) # -> g # Range of elements between index 0 and index 2, element at index 2 is excluded print(str1[0:2]) # -> Py # [start] can be omitted. print(str1[:2]) # -> Py # [stop] can be omitted. print(str1[2:]) # -> thon String # Range of elements from index 2 to the end. print(str1[2:len(str1)]) # -> thon String # Last three characters. print(str1[-3:]) # -> ing # Slicing from start to end, easy way to make a copy. print(str1[:]) # -> Python String # By choosing [step] to be -1, we get the reverse of original. print(str1[::-1]) # -> gnirtS nohtyP

Hea teada: Olemasolevat sõne saab muuta ainult uue sõne loomisega, sest sõne on muutumatu (immutable) andmetüüp.

# no pec aircraft = "Douglas DC-3" # Reassigning a new string to variable. The previous value is deleted. aircraft = "Hawker Hurricane" print(aircraft) # -> Hawker Hurricane supermarine = "Supermarine Spitfire" supermarine_new = supermarine[:12] + "Seafire" print(supermarine) # -> Supermarine Spitfire print(supermarine_new) # -> Supermarine Seafire supermarine.upper() print(supermarine) # -> Supermarine Spitfire supermarine = supermarine.upper() # Reassigning a new string to variable. print(supermarine) # -> SUPERMARINE SPITFIRE
Soovitatavad liselugemise lingid selgitamaks, mis on muutumatute (immutable) ja muutuvate (mutable) objektide vahe: