1

I am new to Python. Have a question regarding join function.

masterlist = [
    ('ap172', ['33', '212-583-1173', '19 Boxer Rd.', 'New York', 'NY', '10005']),
    ('axe99', ['42', '212-582-5959', '315 W. 115th Street, Apt. 11B', 'New York', 'NY', '10027'])
]

I want to print each element of list delimited by pipe.

If I try:

for i in masterlist:
    mystring = '|'.join(i)                                      
    print mystring

The error is:

TypeError: sequence item 1: expected string, list found

So I am trying:

for i in masterlist:
    mystring = i[0] 
    mystring += '|'.join(i[1])                                  
    print mystring

and I get:

ap17233|212-583-1173|19 Boxer Rd.|New York|NY|10005
axe9942|212-582-5959|315 W. 115th Street, Apt. 11B|New York|NY|10027

So it works but would like to know if there is a better way to join the above masterlist using join function?

3
  • I don't know if this is what you meant to do, but the first two elements, ie 'ap172' and '33', aren't being separated by a pipe. Commented Sep 26, 2011 at 21:45
  • Thanks. Yes the first two elements should be separated. Commented Sep 27, 2011 at 13:15
  • Thanks everyone for the replies !! Commented Sep 27, 2011 at 20:05

4 Answers 4

3

I think splitting up the tuples in the for loop would be cleaner.

for identifier, data in masterlist:
     print "%s%s" %(identifier, '|'.join(data))
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, To get what I was trying I modified the last statement to: print "%s%s%s" %(identifier, '|', '|'.join(data)) Thanks!
2
from itertools import chain
for symbol, items in masterlist:
    print "|".join(chain( [symbol], items))

Comments

1

To get what you got you can try

for i in masterlist:
    print i[0] + '|'.join(i[1])

To get what I think your after you can try this

for i in masterlist:
    print i[0] + '|' + '|'.join(i[1])

There are many many ways to do this, these are just 2.

Comments

1
for i in masterlist:
    print '|'.join([i[0]] + i[1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.