3

I am making a string calculator using numbers. For example: 154 + 246 = 154246

So the user will enter an input of a group of numbers, to separate the numbers using \n. As you know, \n is used to make a new line, but I need to use at as any normal string. I need to separate the numbers using \n into a list.

Code:

num_list = [] # this function will add a number to the list def ask_num(): # ask for a number (we will make it a string so we can add comma and /n) num = input("Enter numbers: ") # run the function for asking numbers ask_num() 
5
  • 7
    /n is not used for a new line. \n is. Commented Mar 18, 2022 at 14:23
  • Are you trying to append strings together, or make a calculator that takes strings as input? Your example of 154 + 256 = 154256 looks like just appending? Commented Mar 18, 2022 at 14:26
  • The elements in the list will not be separated by anything unless you put the list in a string and then work on the string later on. Commented Mar 18, 2022 at 14:28
  • Yes, putting them beside each other in order Commented Mar 18, 2022 at 14:28
  • Oh okay. thanks! everyone! thx Commented Mar 18, 2022 at 14:29

3 Answers 3

5

You can use

r"\n" 

or

"\\n" 
Sign up to request clarification or add additional context in comments.

3 Comments

Right, you can use the prefix r to prevent escape sequences to be executed. +1
The r"\n" seems to work properly, IDK why rest solutions don't work, just leaves a \\ at the start of each num
Just for other people to understand:
5

You can escape the \n using an other \.

>>> print("\\n") \n >>> print("\n") >>> print("/n") /n 

In your case, you asked for /n, which is not used for a newline, so you can normally use it in a string.

1 Comment

I just sometimes confuse between the both!
1

Successful solution:

def ask_num(): num_list = [] # ask for a number (we will make it a string so we can add comma and /n) num = input("Enter numbers: ") # put the num in the list num_list.append(num) # seperate the numbers num_list = num.split(r"\n") # print the list print(num_list) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.