简体   繁体   中英

Problem when concatenating lists to string with newline

I would like to concatenate 2 lists with new line.

list1 = [1,2]
list2 = [3,4,5]

The expected output format is:

1,2
3,4,5

My code is:

final = []
final.append(list1)
final.append(list2)

final = '\n'.join([str(i) for i in finallist])

But it returns:

'[1, 2]\n[4, 5, 6]'

Because I am going to save this output to txt file, so it has to be a string and print() does not work here. Could anyone advise how can I solve this problem? Thank you very much!

does this fix your issue (its your expected output):

list1 = [1,2]
list2 = [3,4,5]

final = [list1, list2]

final = '\n'.join([str(i).replace('[', '').replace(']', '') for i in final])
with open('yourfile.txt', 'w') as file:
    file.write(final)

Consider the operations here:

final = []  # An empty list
final.append(list1)  # List contains a list: [[1, 2]]
final.append(list2)  # List contains 2 lists: [[1, 2], [3, 4, 5]]

[str(i) for i in finallist]  # Convert each list into a string, put it in a new list
# e.g. This list will contain two values: ['[1, 2]', '[4, 5, 6]']

It sounds like you want to have commas between values in the list, and newlines between lists. Converting the entire list into a string will include the brackets, when you just want to convert each entry into its own string. Like so:

list1 = [str(i) for i in list1]
list2 = [str(i) for i in list2]
final = [list1, list2]
print('\n'.join([','.join(i) for i in final]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM