'newline charachter use in typecasting
so i just started learning python so please be humble i am still a noob so this is my code
x="hello world"
y=45
z=45.7
w=65
v="harry"
print(y+z)
print(y+w)
print(x+v)
print(type(x))
print(type(y))
print(type(z))
#read explanation from notes
#lets start with typecasting
m="52"
n="34"
print(m+n)
print(int(m)+int(n))
print(float(m)+float(n))
#this code is for conversion into different types
x=5
print(x*"hello world \n")
print(x*"hello world")
print(x*str(int(m)+int(n)))
here in the last statement i tried to print it with a new line character like this
print(X*str(int(m)+int(n)\n))
and this input returned an error like this
print(x*str(int(m)+int(n))\n)
^
SyntaxError: unexpected character after line continuation character
i tried inserting the newline character here and there but it did not work how do i make it print in new lines using new line character
Solution 1:[1]
You need to use + to concatenate strings. You also have to put \n inside quotes. And add parentheses to specify the grouping, since * has higher precedence than +.
print(x * (str(int(m) + int(n)) + "\n"))
You can also simplify this by using a format string.
print(x * f'{int(m)+int(n)}\n')
Solution 2:[2]
To use the newline character you have to surround it with quotation marks like this "\n" or '\n'. Otherwise it won't be interpreted as a string.
So your command could look like this print((x*str(int(m)+int(n)))+"\n") if you want to print the newline once or like this print(x*(str(int(m)+int(n))"\n")) if you need a newline after each (str(int(m)+int(n).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | luca |
