-1

I have this code and want to remove the 'and' from the list.

def names_to_apa(names):
    x = names.split(",")  
    nm = []
    for y in x:
        nm.append(y.split())
    print(nm)
    for i in nm:
        if i == 'and':
            nm.remove(i)
    print(nm)

print(names_to_apa("First Last, David Joyner, and George Burdell"))
#print: Last, F., Joyner, D., & Burdell, G.

The current output is:

[['First', 'Last'], ['David', 'Joyner'], ['and', 'George', 'Burdell']]

but I want to get rid of the 'and' in the third list.

What I have tried doesn't work and what I have found by searching StackOverflow seems to only apply to single lists, or I can't figure out how to implement it in a list within a list.

Can you help?

william3031
  • 1,653
  • 1
  • 18
  • 39

2 Answers2

1

You need to access the sublist to do the removal, not the outer:

data = [['First', 'Last'], ['David', 'Joyner'], ['and', 'George', 'Burdell']]

for sublist in data:
    while "and" in sublist:
        sublist.remove("and")
flakes
  • 21,558
  • 8
  • 41
  • 88
0

try this you can add one instruction in your code to replace the "and" by "":

def names_to_apa(names):
    names=names.replace("and","")
    x = names.split(",")
    nm = []
    for y in x:
        nm.append(y.split())
    print(nm)
    for i in nm:
        if i == 'and':
            nm.remove(i)
    print(nm)

print(names_to_apa("First Last, David Joyner, and George Burdell"))

output:

[['First', 'Last'], ['David', 'Joyner'], ['George', 'Burdell']]
Ghassen
  • 764
  • 6
  • 14