'How to save " \\n " when removing " \n " in string

>>> b = 'first \\n second \n third \\n forth \n fifth \\n'
>>> print(b)
first \n second 
 third \n forth 
 fifth \n

b to wanted result,
print( result )
first \n second third \n forth fifth \n
result = 'first \n second third \n forth fifth \n'
how to do this?



Solution 1:[1]

\n is an escape character, which indicates a line break, while \\n is a backslash and a letter n, which will not be affected when you delete \n:

>>> b = 'first \\n second \n third \\n forth \n fifth \\n'
>>> b.replace('\n', '')
'first \\n second  third \\n forth  fifth \\n'

This example may make you realize the difference between them:

>>> len('\n')
1
>>> list('\n')
['\n']
>>> len('\\n')
2
>>> list('\\n')
['\\', 'n']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1