I want to output a list separated by commas in Python.

Asked 1 years ago, Updated 1 years ago, 342 views


To print the contents of a list as comma-separated text What should I do?

["dog", "cat", "pig"] I would like to write the following list in the text.

 Dogs, cats, pigs

If you execute the code below,

str_li=["dog", "cat", "pig"]

with open('test.txt', 'w', encoding='utf-8') asf:
    for x instr_li:
        f.write(x)

Run Results (test.txt)

Dogs, cats, pigs
with open('test.txt', 'w', encoding='utf-8') asf:
    for x instr_li:
        Concatenated with new_x=", ".join(x)#join
        f.write(new_x)

It looks like the following.

Dogs, piglets

python python3

2022-12-09 13:36

4 Answers

The join returns the merged string, so you don't have to use for to extract the contents of the list.

str_li=["dog", "cat", "pig"]

f=open('test.txt', 'w', encoding='utf-8')
f.write(", ".join(str_li))
f.close()

If you want to use with to avoid forgetting to close the file,

with open('test.txt', 'w', encoding='utf-8') asf:
    f.write(", ".join(str_li))

will be


2022-12-09 17:39

It probably doesn't need to be looped, just create a pre-connected string and write it down.

example:

str_li=["dog", "cat", "pig"]
new_x=", ".join(str_li)

with open('test.txt', 'w', encoding='utf-8') asf:
    f.write(new_x)


2022-12-09 19:58

str_li=["dog", "cat", "pig"]

with open('test.txt', 'w', encoding='utf-8') asf:
    print(*str_li, sep=',',', file=f)

Run Results

$cattest.txt
dogs, cats, pigs


2022-12-09 20:05

Just in case, I added a numerical list.

str_li=['dog', 'cat', 'pig']
num_li = [1,2,3]

with open('test.txt', 'w', encoding='utf-8') asf:
    f.write(','.join(str_li)+'\n')
    f.write(','.join([str(x)for x in num_li]) + '\n')

with open('test.txt', 'r', encoding='utf-8') asf:
    print(f.read(), end='')
 Dogs, cats, pigs
1,2,3


2022-12-10 01:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.