Search code examples
pythonfor-loopslice

Slicing in a list element of string and also in each character of the list element


I have the following code code:

people = ['Vianney', 'Mariana', 'Ignacio', 'Gaspar']
index = 0
for name in people:
    print(name, '\n')
    name1 = name
    for name in name1:
        print(name1[index], end =' ')
        if name[index] < name1[index]:
            index = index + 1
        else:
            break

I want to slice on a list of elements of string and also in each character of the list element selected. Using only for in in python

This is the result I got:

Vianney

V Mariana

M Ignacio

I Gaspar

G

and, I want this:

Vianney

V i a n n e y

from each element


Solution

  • It's unclear what you're trying to achieve with the index and the comparison.

    It seems like all you want to do is:

    people = ['Vianney', 'Mariana', 'Ignacio', 'Gaspar']
    
    for name in people:
        print(name)  # print the name
        for character in name:
            print(character, end=' ')  # print each character from the name
        print()  # print a line ending after the letters and spaces
    
    

    Output:

    Vianney
    V i a n n e y 
    Mariana
    M a r i a n a 
    Ignacio
    I g n a c i o 
    Gaspar
    G a s p a r