0
Can someone explain to me this output?
def change(x,word): if x in word: pos=word.index(x) try: word=word[pos:3]+word[pos-3] except: word=“Error occurred!” return word print(change(“F”,”False”)) I am not sure why the outcome is Fall, can someone kindly explain?
2 Respostas
+ 6
At first the position of F is found, which is 0 (sind F is the first character).
word[pos:3] is then word[0:3], it gives you the first three letters, i.e. "Fal"
word[pos-3] is word[-3], i.e. you go backwards in your original string
word[-1] would be "e", word[-2] is "s" and word[-3] is "l"
Now the two strings word[0:3] and word[-3] are concatenated by the plus operator.
So "Fal" + "l" then returns "Fall"
+ 2
THEGreatGatsby , pos => 0 (index of "F" is 0). Then slice the string and concatenate the parts => first part is "Fal" (index 3 is excluded, this part is formed from indexes from 0 to 2), second part is word[0 - 3] => word[-3] ( counting backwards the string) => "l". So the result is "Fal" + "l" => "Fall".