![]() |
How to prevent python from going to new line in for loop? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to prevent python from going to new line in for loop? (/thread-23750.html) |
How to prevent python from going to new line in for loop? - idknuttin - Jan-15-2020 For example, let's say I want to go through each character in a string and print it like this for x in "Python": print(x)This prints P y t h o nHow do I make it print this instead? PythonMy second question is when I print two variables how do I avoid printing the white space in between them? for example when I type this: x = 5 y = 6 print(x, y)it prints this 5 6but I want it to print it like this with no white space in between the 5 and 6 56 RE: How to prevent python from going to new line in for loop? - prateekshaw - Jan-15-2020 Hi, Check this https://docs.python.org/3/library/functions.html#print for x in "Python": ...: print(x,end='') print(x,y,sep='')So basically every print automatically add \n to end that is reason why we see next line. But we can override this by setting end value. RE: How to prevent python from going to new line in for loop? - jefsummers - Jan-15-2020 Don't forget Python's built in help system. For example: >>> help(print) Shows that print() is pretty handy - can use to write to files, create an easy csv file (print to file and use sep=", "), use a newline or not, etc.
RE: How to prevent python from going to new line in for loop? - deanhystad - Feb-11-2022 You can format what is printed. I like this as it gives me total control. x, y = 5, 6 print(f"My numbers are ({x},{y})") As for printing multiple prints on one line, you can do that with stdout.write() and print(end=""), but I prefer not doing multiple prints.This is a bit of code I extracted from a tic-tac-toe game. In uses str formatting and str joining to print out the tic-tac-toe board. class Board(): def __init__(self, board): self.board = list(board) def __str__(self): rows = [f" {self.board[i]} | {self.board[i+1]} | {self.board[i+2]}" for i in range(0, 9, 3)] return "\n---+---+---\n".join(rows) winner = "O" ttt = Board("OX OXX O") print(f" The winner is {winner}\n\n{ttt}") By making the entire board a str it is easy to ask the where to place the next "X".pos = input(f"{board}\n {player}: ") |