Home > Back-end >  Join strings in a list with \n in the list (Python)
Join strings in a list with \n in the list (Python)

Time:10-08

Simple question that I couldn't find on Stack. How do I join strings in a list with special characters in the list?

(The dataset indeed contains '/n' instead of the right version of '\n')

For example:

sentence = ['lets', 'make', 'a', 'newline', '/n' ,'now we have made a new line']
' '.join(sentence)

Current output:

>> 'lets make a newline /n now we have made a new line'

Ideal output:

>>'lets make a newline
now we have made a new line'

CodePudding user response:

I believe you made a typo and typed /n instead of \n.

Modify your code by changing the slash with \

sentence = ['lets', 'make', 'a', 'newline', '\n' ,'now we have made a new line']
print(' '.join(sentence))

CodePudding user response:

We don't see that /n in your ideal output and you have to break the it into two lines. So, you can try this

sentence = ['lets', 'make', 'a', 'newline', '/n' ,'now we have made a new line'] 
sentence.remove('/n')
sentence.insert(4,'\n')
print(' '.join(sentence))
  • Related