Search code examples
pythonstringuser-inputnewline

New line character as user input in Python


While joining items in a list and printing them out as a string, I wanted to take user input for a character that will be used a separator. What if the separator is to be a newline? What can the user input be? Because if the user input is simply '\n' then that is being used literally ('\n' is being added as text).

Code that I ran:

tojoin = ['Hello','Its','Me','Uh','Mario']
merge = tojoin[0]
sepchar = input("Enter the character(s) with which you wish to separate the list items:  ")
#User input = '\n'
for i in tojoin:
    merge = merge+sepchar+i
print(merge)

Expected output:

Hello

It's

Me

Uh

Mario

Actual output: Hello\nHello\nIts\nMe\nUh\nMario

How can I get to the expected output?


Solution

  • you need to add the following line of code after the input

    sepchar = bytes(sepchar, "utf-8").decode("unicode_escape")
    

    source