Home > database >  How to store multiple lines separated by enter value in a single variable in python? Example is in t
How to store multiple lines separated by enter value in a single variable in python? Example is in t

Time:04-02

555
554
33
2444
4555
2455
24555
2555
2335
5555
23455
2455
2344

I want to store all these values in the single variable num, how can I do that?

CodePudding user response:

If you are working with a multiple line string you can use split given "\n" as the splitor:

myString = """
555
554
33
2444
4555
2455
24555
2555
2335
5555
23455
2455
2344
"""
myString.strip().split("\n")

Output

['555',
 '554',
 '33',
 '2444',
 '4555',
 '2455',
 '24555',
 '2555',
 '2335',
 '5555',
 '23455',
 '2455',
 '2344']

Note that if you are working with file, you can still use the same approach, but you need to read the file first.

CodePudding user response:

num=list(555, 554, 33, 2444, 4555, 2455, 24555, 2555, 2335, 5555, 2345, 2455, 2344)

CodePudding user response:

You can simply use \n in python to create a new line. For example, this prints out what your example to the console: print("555\n554\n33\n2444\n4555\n2455\n24555\n2555\n2335\n5555\n23455\n2455\n234")

If you wanted to write something to a file, you can do something similar to:

numbers = [number, number, more_numbers]  # Create a list containing numbers
file = open("file.txt", "w")  # Opens file.txt in write mode 
for number in numbers:  # Loop through the numbers in list
    file.write(number\n)  # Writes numbers with line breaks after each one in the list

If you simply wanted to print out the numbers in the list, replace the file.write(number\n) with print(number\n). And remove the file = open line. You can always use \n to create a new line.

  • Related