+ 2
return str[n] = Output is 'i' for sure but return str[n:] = Output is 'ing' (can somebody explain)
4 Answers
+ 6
The keyword is slicing...
You can define a slice of a string by syntax strng[a:b].
This will return the slice of strng between index a (including) and index b (excluding).
For example:
string1 = "Sololearn"
string2 = string1[2:7] #lolea
Special cases:
[:7] #omitted first argument is replaced by 0
[3:] #omitted second argument is replaced by length (last index + 1)
In your example:
"string"[3:] == "ing" #from idx 3 to end
+ 6
First try not to use str as an identifier in your future code. str is already a predefined type and you could end up redefining it and unintentionally causing yourself hard to find errors in your code.
s[3] will return the element at the index of 3
Where s[3:] is a slice and will return a slice beginning at the index of 3, and since the second index is omitted, will continue to the end of the string.
Likewise, s[:3] would start at the beginning of the string and end at index 3.
+ 3
The "[n:]" return "ing" because it starts from the index n which is 3 and remove what is before it so from "string" it will only remain "ing"
+ 3
when you define your string, it is a list starting at index 0 until the end (in this case "String" = ['S', 't', 'r', 'i', 'n', 'g'] with index from 0 to 5).
its n is 3, so it will start from index 3, that is: [3:] = ['i', 'n', 'g'] = 'ing'.
the other way, where it presents [3] only the letter in index 3 is removed, in this case 'i'.