Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why I'm getting this kind of output?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['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:')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading