Python Forum
How to prevent python from going to new line in for loop?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to prevent python from going to new line in for loop?
#1
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
n
How do I make it print this instead?
Python
My 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 6
but I want it to print it like this with no white space in between the 5 and 6
56
Reply
#2
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.
Reply
#3
Don't forget Python's built in help system. For example:
>>> help(print)
Output:
Help on built-in function print in module builtins: print(...) print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream.
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.
Reply
#4
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})")
Output:
My numbers are (5,6)
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}")
Output:
The winner is O O | X | ---+---+--- | O | X ---+---+--- X | | O
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}: ")
Yoriz write Feb-11-2022, 06:29 AM:
Note the post that this post was replying to has been removed, it was a post of someone that had bumped an old post to show a link advertising a website.
The spammer has been purged.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Using SQLAlchemy, prevent SQLite3 table update by multiple program instances Calab 3 701 Aug-09-2023, 05:51 PM
Last Post: Calab
  Trying to loop through code to plot seaborn line plots across multiple subplots eyavuz21 0 1,574 Dec-05-2022, 10:46 AM
Last Post: eyavuz21
Smile How we can prevent screen recording murad_ali 3 1,757 Jul-29-2022, 10:29 AM
Last Post: DeaD_EyE
  Skipping line in text without Restarting Loop IdMineThat 4 1,433 Apr-05-2022, 04:23 AM
Last Post: deanhystad
  How to make for loop display on 1 Line Extra 3 1,376 Jan-12-2022, 09:29 PM
Last Post: Extra
  multi-line CMD in one-line python kucingkembar 5 3,861 Jan-01-2022, 12:45 PM
Last Post: kucingkembar
  Prevent urllib.request from using my local proxy spacedog 0 2,803 Apr-24-2021, 08:55 PM
Last Post: spacedog
  Prevent a PDF from being edited using Python? PythonNPC 1 2,231 May-05-2020, 09:04 PM
Last Post: micseydel
  How to prevent Command Promt from closing when I turn it off in Python? binhduonggttn 1 1,958 Mar-06-2020, 10:12 AM
Last Post: ibreeden
  Can i prevent the random generator to generate already used numbers? MauserMan 3 2,806 Jan-05-2020, 04:44 PM
Last Post: MauserMan

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020