简体   繁体   中英

python convert list to string with newlines

Mostly likely there is some really stupid mistake, however i'm completely stuck on this and not getting what is wrong:

Trying to convert a list to string with newlines for each list element:

        meta_temp = ['name: {}; content: {};'.format(el['name'], el['content']) for el in self.meta]
        for hop in meta_temp:
            print(hop)

        self.meta = '\n'.join(map(str, meta_temp))

        for op in self.meta:
            print(op)

list meta_temp consists of the str objects and for hop in meta_temp: print(hop) shows the correct representation -

name: generator; content: zmvc; 
name: viewport; content: width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0; 

and so on.

However, after trying to convert to a string '\\n'.join(map(str, meta_temp)) , i'm getting the string with newlines after each character , like ( for op in self.meta: print(op) ):

n
a
m
e
:

tried:

'\n'.join(map(str, meta_temp))
'\n'.join(meta_temp)
''.join(map(str + '\n', meta_temp))
'\n'.join(el for el in meta_temp))

Using python 3.5

looked into different sources and google it... what am i doing wrong here? Understand that most likely i'm just blind and missing some small thing. If you minus - please point me on the mistake.

self.meta is a string. Trying to iterate it with for op in self.meta and print elements will print one charater at a time. Just print it using print(self.meta) and you'll see the newline separated string printing correctly.

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