Jin
Jin

Reputation: 1223

output list of special letters string with python

I have 2 lists of strings, they are constructed from database content but I have difficulty in reading it into a txt file

list_a={u'XYZ-123-456',u'XYZ-123-456',u'XYZ-789-456',....}

list_b={u'Tom \n is creative', u'Sky is blue',....}

What I need to do is get rid of 'u' at the beginning of each string in both lists, getting rid of \n within each string in list_b where applicable.

then write each element in list_b to a text file, one by a line, into the txt file, whose title is the element in list_a. Strings with the same title should be in the same txt file. Anyone can help ?

I think I can use pop function to get rid of u, but how about the '\n' within the string? I am also not 100% sure about the I/O function. Anyone can help me out with the sample script?

Thanks a lot, a newbie of python

Upvotes: 0

Views: 132

Answers (1)

Rich Tier
Rich Tier

Reputation: 9441

Welcome so SO.

list_a is actually a set. The {} indicates set, which is a list of unique items - so you may not want this type if you expect multiple values in the 'list'. If you want an actual list then encapsulate the 'list' with [...] instead of {...}

The 'u' in the set indicates the text is unicode. if you want this removed:

list_a = map(str, list_a)

\n is a control character indicating a new line. This will be represented as a new line when printed in the console. If you really don't want new lines then do:

list_b= { item.replace('\n','') for item in list_b }

I assume you want each item on a new line in the text file. If so:

with open('c:\file.txt', 'w') as file:
    file.write('\n'.join(list_a)) 
    file.write('\n'.join(list_b)) 

for non duplicates merge the 2 lists into a set. As they are currently already sets this will work:

with open('c:\file.txt', 'w') as file:
    file.write('\n'.join(list_a + list_b)) 

Upvotes: 1

Related Questions