Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new line character to a variable in python [duplicate]

Tags:

python

I have the below function to get the below output

22
4444
666666

Instead i'm getting

'22\n4444\n666666\n88888888\n'

Any ideas where im going wrong?

def EvenLadder(n):
    ...:     solution = ''
    ...:     if n <= 1:
    ...:         return solution
    ...:     elif n%2 ==0:
    ...:         for i in range(2,n+1,2):
    ...:             solution += (str(i)*i)+"\n"
    ...:     else:
    ...:         n = n - 1
    ...:         for i in range(2,n+1,2):    
    ...:             solution += (str(i)*i)+"\n"
    ...:     return solution
like image 932
Kannaj Avatar asked Sep 27 '22 07:09

Kannaj


People also ask

How do you add a new line after a variable in Python?

Use the addition operator to print a new line after a variable, e.g. print(variable + '\n') . The newline ( \n ) character is a special character in python and is used to insert new lines in a string.

How do you fix a new line in Python?

Just use \n ; Python automatically translates that to the proper newline character for your platform.

How do you add n to a string in Python?

You can just use n for specifying a newline character, and Python will translate it to the appropriate newline character for that platform.

How do you insert a break in Python?

The new line character in Python is used to mark the end of a line and the beginning of a new line. To create a string containing line breaks, you can use one of the following. Newline code \n(LF), \r\n(CR + LF).


1 Answers

'22\n4444\n666666\n88888888\n' is the correct string representation of the expected result. In order to actually process the newline characters you need to print it:

print EvenLadder(6)
like image 138
enrico.bacis Avatar answered Sep 29 '22 19:09

enrico.bacis