简体   繁体   中英

Concatenate the two strings side by side separated by a space?

I want to concatenate two strings side by side. However, when I run my code the strings are saved one below the other. I want it to be side by side separated by a space.

path = '../data/img'
mask = '../data/canny_mask'
text_file = open("train.lst", "w")
for file in os.listdir(path):
    img_name = file[:]

for file in os.listdir(mask):
    mask_name = file[:]
    text_file.write(str('data/img')+str(img_name)+'\n')+text_file.write(str('data/canny_mask')+str(mask_name)+'\n')

text_file.close()

Here, you are calling text_file.write() twice:

text_file.write(str('data/img')+str(img_name)+'\n')+text_file.write(str('data/canny_mask')+str(mask_name)+'\n')

In the first call, there's a newline character '\\n' . If you want a space instead of a newline, change the code at that point.

I also recommend to not put a + between the two calls. Write them in separate lines, or make only one call.

Something like this might help:

for file in os.listdir(mask):
    mask_name = file[:]
    " ".join('data/img', str(img_name), 'data/canny_mask', str(mask_name))

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