This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 1 year ago.
I have one problem with print in Python, I am starting to learn Python, but when I want to print variables in print function, it looks like that after one variable it adds newline to the outcome:
print(game_name + " | " + rating)
I am making a game database with my own ratings on the games but if it prints the game and the rating there is like one empty line belpw the game_name and rating is written, how can I delete that empty newline? I am very new to this, so please don't be mean...
Welcome to Stack Overflow! The most likely culprit is that there is a newline at the end of the game_name variable. The easy fix for this is to strip it off like this:
print(game_name.strip() + " | " + rating)
Say we had two variables like this.
game_name = 'hello\n'
rating = 'there'
game_name has the newline. To get rid of that use strip().
print(game_name.strip() + " | " + rating)
output
hello | there
If you want to remove the line break after printing, you can define the optional end parameter to the print statement.
print('Hello World', end='') # No new line
If your variable has a new line added to it, and you want to remove it, use the .strip() method on the variable.
print('Hello World\n'.strip()) # No empty line
For your code, you could run it:
print(game_name + " | " + rating, end='')
Or
print(game_name + " | " + rating.strip())
If the error is that a new line is printed after game_name, you'll want to call the strip method on that instead.
print(game_name.strip() + " | " + rating)
rating or game_name most likely have a new line after the specified string.
You can fix it by doing this:
game_name = game_name.strip('\n')
rating = rating.strip('\n')
print(game_name + " | " + rating)
Related
This question already has answers here:
Getting SyntaxError for print with keyword argument end=' '
(17 answers)
Closed 8 years ago.
This is the function for printing all values in a nested list (taken from Head first with Python).
def printall(the_list, level):
for x in the_list:
if isinstance(x, list):
printall(x, level=level + 1)
else:
for tab_stop in range(level):
print("\t", end='')
print(x)
The function is working properly.
The function basically prints the values in a list and if there is a nested list then it print it by a tab space.
Just for a better understanding, what does end=' ' do?
I am using Python 3.3.5
For 2.7
f = fi.input( files = 'test2.py', inplace = True, backup = '.bak')
for line in f:
if fi.lineno() == 4:
print line + '\n'
print 'extra line'
else:
print line + '\n'
as of 2.6 fileinput does not support with.
This code appends 3 more lines and prints the appended text on the 3rd new line. and then appends a further 16 empty lines.
The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed
Eg: - print ("hello",end=" +") will print hello +
See the documentation for the print function: print()
The content of end is printed after the thing you want to print. By default it contains a newline ("\n") but it can be changed to something else, like an empty string.
I'm writing a short program to go through a directory and write create table and load from csv statements for a bunch of csvs and get them all into mySQL. I'm sure there's an easier way to do this, but I thought it would be fun to make it myself.
This is one of the lines I have in python to build the load csv statement, where l_d is a variable I'm storing it in, f is the file path, and n is the table name:
l_d = "LOAD DATA INFILE " + "'" + f + "'" + "\nINTO TABLE " + n + "\nFIELDS TERMINATED BY ','\nENCLOSED BY '" + '"' +"'" + "\nLINES TERMINATED BY" +"\'\n\'" + "\nIGNORE 1 ROWS;"
The statement I want in SQL is:
LOAD DATA INFILE 'file.csv'
INTO TABLE table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY'\n'
IGNORE 1 ROWS;
but what I get is always
LOAD DATA INFILE 'file.csv'
INTO TABLE table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY'
'
IGNORE 1 ROWS;
because it thinks my \n is supposed to be a line break and not the actual characters.
How can I get the actual characters to show up here?
Also, I know my whole string concatenation in the original statement is kinda gross (I'm pretty new to this), so any general tips on how to improve that would also be much appreciated :)
to escape the backspace add another one before it:
\\n
gets \n
so your code will be:
l_d = "LOAD DATA INFILE " + "'" + f + "'" + "\nINTO TABLE " + n +
"\nFIELDS TERMINATED BY ','\nENCLOSED BY '" + '"' +"'" + "\nLINES
TERMINATED BY" +"\'\\n\'" + "\nIGNORE 1 ROWS;"
print("hello\ \n")
#this print a original "\n"
This question already has answers here:
I have wrong results with sorting function at python
(2 answers)
Closed 2 years ago.
Im trying to write a code where user puts in their score (a number), and then they put in their name. both the score and name gets stored in a text file (alongside with '\n', so that every new couple gets stored on the new line).
hscores = open("highscores.txt", "a")
hscores.write(str(score))
hscores.write(" ")
hscores.write(nickname)
hscores.write("\n")
hscores.close()
then, I open the text file, take every input in there, sort it by highest to lowest and output it:
hscores22 = open("highscores.txt", "r")
listings2 = hscores22.readlines()
sorting2 = sorted(listings2, reverse=True)
print "| 1 | " + sorting2[0]
print "| 2 | " + sorting2[1]
print "| 3 | " + sorting2[2]
print "| 4 | " + sorting2[3]
print "| 5 | " + sorting2[4]
print "| 6 | " + sorting2[5]
print "| 7 | " + sorting2[6]
print "| 8 | " + sorting2[7]
print "| 9 | " + sorting2[8]
print "| 10 | " + sorting2[9]
The problem is that python thinks that number that starts with the biggest number, is bigger, for example: 90>1000, 50>100 (I suppose thats because i have to convert all the numbers to strings before storing them in the text file). is there any way i could fix this?
thanks in advance.
Since you're sorting strings, Python is comparing them lexicographically - so '2' is bigger than '1'. You need to extract the numeric part of your string, convert it to a number and use this number for sorting key:
sorting2 = sorted(listings2, reverse=True, key=lambda x: int(x.split()[0]))
BTW, next 10 lines really ask to be replaced by a for loop…
i am very new in python (and programming in general) and here is my issue. i would like to replace (or delete) a part of a string from a txt file which contains hundreds or thousands of lines. each line starts with the very same string which i want to delete.
i have not found a method to delete it so i tried a replace it with empty string but for some reason it doesn't work.
here is what i have written:
file = "C:/Users/experimental/Desktop/testfile siera.txt"
siera_log = open(file)
text_to_replace = "Chart: Bar Backtest: NQU8-CME [CB] 1 Min #1 | Study: free dll = 0 |"
for each_line in siera_log:
new_line = each_line.replace("text_to_replace", " ")
print(new_line)
when i print it to check if it was done, i can see that the lines are as they were before. no change was made.
can anyone help me to find out why?
each line starts with the very same string which i want to delete.
The problem is you're passing a string "text_to_replace" rather than the variable text_to_replace.
But, for this specific problem, you could just remove the first n characters from each line:
text_to_replace = "Chart: Bar Backtest: NQU8-CME [CB] 1 Min #1 | Study: free dll = 0 |"
n = len(text_to_replace)
for each_line in siera_log:
new_line = each_line[n:]
print(new_line)
If you quote a variable it becomes a string literal and won't be evaluated as a variable.
Change your line for replacement to:
new_line = each_line.replace(text_to_replace, " ")
In order to create a progress bar that show the lode by present
The thinking behind it was to erase the line and then rewrite it so it will look like the current precent.
I tried to do this:
import time
---some kind of loop---:
... downloading stuff ...
b = str((prhelp / 576)*100)
print(b + "%", end="\r")
time.sleep(1)
prhelp = prhelp + 1
But it just don't printing any thing
Also I would like to know how to print a number only 3 digits after the dot -
12.345678 --> 12.345
So my program won't print too long precent
it's because when you print, you give the parameter end is the string that will be added to the end. By default, it's \n. You gave \r. What this character means is remove the current line. That's why it doesn't print a thing...
If you want it to work, your replace this:
print(b + "%", end="\r")
by:
print(b + "%")
What I'm guessing you want is:
import time
print('Hello', end='')
time.sleep(1)
print('\rworld!')
This code will print Hello, wait 1 second, and then replace the Hello by world!
At the end I just needed to do:
import time
b = str(round((prhelp / 576) * 100,3))
print('\r',end = "")
print(b + "%",end = "")
time.sleep(0.01)
prhelp = prhelp + 1
By doing
print('\r',end = "")
I'm removing the last line and makeing place for the next number im writing.
Thanks for all the helpers