Home > Enterprise >  how do i replace a string in a list
how do i replace a string in a list

Time:11-23

Im trying to change a string in a list called lista composed by n times |_|, in a function I'm trying to change one specific place of the list with "X" but nothing is working

lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]

i want to change only the middle one to |X|

I already tried different methods like, the command replace or pop and then insert a new value but nothing as changed and always gives me an error

CodePudding user response:

This code places "|X|" in the middle of the list:

if len(lista)%2==0:
    lista[int(len(lista)/2)-1]='|X|'
    lista[int(len(lista)/2)]='|X|'
else:
    lista[int(np.floor(len(lista)/2))]='|X|'

Output When len(lista)==10

['|_|', '|_|', '|_|', '|_|', '|X|', '|X|', '|_|', '|_|', '|_|', '|_|']

Output When len(lista)==11

['|_|', '|_|', '|_|', '|_|', '|_|', '|X|', '|_|', '|_|', '|_|', '|_|', '|_|']

CodePudding user response:

Use len(lista) // 2 to get the middle index.

Should there be an un-even number, // 2 will 'round' it to the previous integer, so 9 --> 4

lista = [ "|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|" ]
middle = len(lista) // 2

lista[middle] = '|X|'

print(lista)
['|_|', '|_|', '|_|', '|_|', '|_|', '|X|', '|_|', '|_|', '|_|', '|_|']

Try it online

CodePudding user response:

lista=["|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|","|_|"]
lista[ round(len(lista)/2)-1 ] = '|X|'

Output:

['|_|', '|_|', '|_|', '|_|', '|X|', '|_|', '|_|', '|_|', '|_|', '|_|']

Use -1 because indexes starts from 0

  • Related