I have an array in python that has letters as strings and a comma as a string also. I have managed to find code that finds all the letters that come before that comma letter, there are other comma letters and i would like to iterate to list every letter that comes before the commas in the array here is what i got so far

##THE ARRAY IS THIS ONE
myarray=['G', 'o', 'T', ',', 'I', 't', 'B', ',', 'M', 'N', 'R', ',', 'K', 'F', 'P', ',', 'M', 'F', 'I', 'H', ',', 'A', 'H', ',']
temp = myarray.index(",")
res = myarray[:temp]
print(res)

##tHE CODE ABOVE outputs ['G','o','T'], is there a way in which i can iterate through all elements in 
the array listing every letter that comes before the commas

I'm not sure I follow. Can you please specify the exact output you want for the given input?

Incidentally, an easier way to initialize that list is

myarray = 'G o T , I t B , M N R , K F P , M F I H , A H ,'.split()

If you want to combine a list of strings into a single string, use the string .join() method:

    res = ''.join(myarray[:temp])
    print(res)

If you don't need that res string for later use, Python 3 has a neat way to expand a list into separate arguments to print(), or any other function. For print, there's normally a space inserted between arguments, but you can change that using the sep= keyword. Try these two statements to see what I mean:

    print(*myarray[:temp]) # print selected items separately
    print(*myarray[:temp], sep='') # no spaces this time       

Another neat trick with that is to use sep='\n' to print each list item on its own line. You don't need that for your current problem, of course, but it's handy to know about.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.