Issue
I run this code on my desktop and and I enter watermelon
and code run ok but it split watermelon letter by letter
fruits = ['apple','pine','grape','mango','orange']
fruits[1:3] = input('Enter a fruit:')
print(fruits)
Output:
Enter a fruit: watermelon
['apple','w','a','t','e','r','m','e','l','o','n','mango',orange']
Expected output:
['apple','watermelon','mango','orange']
Solution
Since you're doing slice assignment, the source will be treated as a sequence. The slice [1:3]
will be replaced by each element of the source sequence separately.
When a string is used as a sequence, each character is a separate element, so it gets split up and inserted into the list.
If you want to replace the slice with the whole string, wrap it in a list.
fruits[1:3] = [input('Enter a fruit:')]
Answered By - Barmar Answer Checked By - Robin (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.