PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

[FIXED] Why I'm getting this kind of output?

 August 15, 2022     character, list, output, python, slice     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing