Replacing \n with actual new line

i am trying to replace \n with actual new line in any string
example: input:“my name\n is\n shivam”
output should be:"my name
is
shivam
but below code is not working please help.#beginer :joy:
s =input()

a=[]

for char in s:

if char=='\n':

    r=s.index(char)

    a.append(s[0:r])

    s=s.replace(s[0:r+1],"")

else:

    continue

print(a)

:thinking:I think that’s because backslash and ‘n’ are being considered as 2 different characters.
image
Why can’t you go with simple split function.

2 Likes

Python automatically escapes the user input, so

my name\n is\n shivam

will be in python as

my name\\n is\\n shivam

that’s why it will not take \n as single character, try using repr(str) to see how python formats it. While, keeping this str in code will take \n as single character.

in python for you to get,your output in such a pattern:
"my name
is
shivam
try this block of code;
print(“My_Name\n”“Is\n”“Shivam”)
example of my code below​:point_down::point_down::point_down:
Screenshot_20210420-012843|250x500

It can be done this way too:

a = input()
i = 0
ans = []                                 #list named ans for putting seperated words
ans.append("")
for x in range(len(a)):                  #iterating through the input
    if a[x] == "\\" and a[x+1] == "n":   #if it is "\n"
        a.replace("\n","\n")
        i += 1
        ans.append("")
    elif (a[x-1] == "\\" and a[x] == "n"):
        pass
    else:
        ans[i] = ans[i] + a[x]
for x in ans:
    print(x)

The logic of this code:
First, we take user input. Then, an list named “ans” is created, where we will put all the ‘parts’ of the answer which are separated by “\n”.
We go through all the elements of the given string and check if we get any “\n”, and if we get “\n”, we create another string in the list “ans”
Then, finally, we print all the elements of the list “ans” on a new line.