'How to make for loop only go to next line only when it finds a \n [duplicate]
Title ^
So I have this code:
from colorama import Fore, Back, Style
#( site kind of glitched out I guess because of all these special characters so thats why it's not in the ``` )
file_contents = " ^^ @@@@@@@@\n ^^ ^^ @@@@@@@@@@@@@@\n @@@@@@@@@@@@@@@@@@ ^^\n @@@@@@@@@@@@@@@@@@@@\n~~~~ ~~ ~~~~~ ~~~~~~~~ ~~ &&&&&&&&&&&&&&&&&&&& ~~~~~~~ ~~~~~~~~~~~ ~~~\n~ ~~ ~ ~ ~~~~~~~~~~~~~~~~~~~~ ~ ~~ ~~ ~\n ~ ~~ ~~ ~~ ~~ ~~~~~~~~~~~~~ ~~~~ ~ ~~~ ~ ~~~ ~ ~~ \n ~ ~~ ~ ~ ~~~~~~ ~~ ~~~ ~~ ~ ~~ ~~ ~ \n~ ~ ~ ~ ~ ~~ ~~~~~~ ~ ~~ ~ ~~\n ~ ~ ~ ~ ~~ ~ ~\n"
#(this is supposed to be an ascii text art of a sunset)
for x in file_contents:
if x == "~":
print(Fore.RED + x)
elif x == "&":
print(Fore.CYAN + x)
elif x == "@":
print(Fore.YELLOW + x)
elif x == "v" or x == "^":
print(Fore.BLACK + x)
And while it does work as expected it prints every single character in a newline and if I put ,end = '' it prints everything in the same line. So how could I make it so that it only goes to a newline if it finds a \n?
(Yes, I know I could technically manually but I'm lazy and that's going to take really long)
Solution 1:[1]
- Set
end=''for all the print statements you already have - Add
elif x == "\n":
print('')
Solution 2:[2]
You can use partial and path the print function: (be cautious!)
from functools import partial
print = partial(print, end='')
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 | nova85861 |
| Solution 2 | Dror Hilman |
