Is there any simple way to add \n in r'' string in python
format, python, string
Solution
The string literal prefix `r` signifies a raw string, that is escape's are regular characters. If you really want to use raw strings, you can try something like:
name = 'new'
des = 'new add one'
newline = '\n'
str_output = rf'name = {name}s, some_dir = \\folder0\\..., description = "{des}s{newline}s'
print(str_output)
Although this means that you'll have to bear the `newline` in every `dict`.
Another way of doing it which has a little more meaning:
str_output = r'name = %(name)s, some_dir = \\folder0\\..., description = "%(des)s%(\n)s'
print(str_output % {'name':'new', 'des':'new add one', '\\n': '\n'})
Problem
I need to add several paths into a single line string with a \n character at the end. For convenience, The key word r is added at the front of the string. In this case the character '\n' couldn't be display normally. Ex. ``` str_output = r'name = %(name)s, some_dir = \\folder0\\..., description = "%(des)s\n' print(str_output % {'name':'new', 'des':'new add one'}) ``` The out put will display without line break. Currently I use string plus to by pass this problem. Such as: ``` str_output = r'name = %(name)s, some_dir = \\folder0\\..., description = "%(des)s' + '\n' ``` Instead of the previous define of str_output. I'm curious about is there any other convenience way to do this? The string plus looks ugly in my codes. Thank you!