Python Forum

Full Version: How to append at a specific position
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This is a little hard to explain but if the code is ran things will start to make sense.

Right now when this program is ran it does this, when I enter a letter in the input that is part of line 1
['*', '*', '*', '*', '*', 'l']

My goal is to have it do this instead
['*', 'l', '*', '*', '*',]


line1 = 'alpha'
line2 = ['*', '*', '*', '*', '*',]
password = input('enter a letter in the password')

for i in line1:
    if i == password:
        line2.append(password)
        print(line2)
Does anyone know the solution?
I would use enumerate and then index assignment.
(Sep-21-2019, 12:57 AM)ichabod801 Wrote: [ -> ]I would use enumerate and then index assignment.

Do you mean doing it this way? It did work if each letter is unique, however when there are two same letters within line 1 it will only detect and replace the first one and igonring the second one.
line1 = 'november'
line2 = ['*', '*', '*', '*', '*', '*', '*', '*',]
password = input('enter a letter in the password')

for i in line1:
    if i == password:
        line2[line1.index(i)] = password
        print(line2)
result of running this code:
['*', '*', '*', 'e', '*', '*', '*', '*']
If I understand the objective correctly one can use zip and conditional expression:

>>> password = 'alpha'                                    
>>> display = '*' * len(password)                         
>>> guess = 'h'                                           
>>> display = ''.join(char if char == guess else star for char, star in zip(password, display))                 
>>> display                                               
>>> '***h*'
(Sep-21-2019, 04:14 AM)perfringo Wrote: [ -> ]If I understand the objective correctly one can use zip and conditional expression:

>>> password = 'alpha'                                    
>>> display = '*' * len(password)                         
>>> guess = 'h'                                           
>>> display = ''.join(char if char == guess else star for char, star in zip(password, display))                 
>>> display                                               
>>> '***h*'

Thanks, I think that just solved the problem, do you have a link to a site or document that explains how this works?
Documentation from python.org:

built-in function zip(),
string method str.join(),
conditional expressions,
generator expression

Python is so concise that expressing it in spoken language is much longer and complicated:

(char if char == guess else star for char, star in zip(password, display))

"generate character if character is equal to guess else generate star for every character - star pair in zipped password and display",

''.join

"join generated chars and stars into string"

display =

Assign value of newly generated string to display (required if one want to repeat the operation)