This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 7 years ago.
I am a new to python programming. I've followed the "Learn python the hard way" book but that is based on python 2x.
def print_one_line(line_number,f):
print(line_number,f.readline())
In this function every time it prints A line and a new line.
1 gdfgty
2 yrty
3 l
I read the documentary that if i put a , (comma) after readline()
then it won't print a new \n.
Here is the documentary:
Why are there empty lines between the lines in the file? The
readline() function returns the \n that's in the file at the end of
that line. This means that print's \n is being added to the one
already returned by readline() fuction. To change this behavior simply add a ,
(comma) at the end of print so that it doesn't print its own .
When I run the file with python 2x then it is OK, but when I do it in python 3x then the newline is printed. How to avoid that newline in python 3x?
Since your content already contains the newlines you want, tell the print() function not to add any by using the optional end argument:
def print_one_line(line_number,f):
print(line_number,f.readline(), end='')
Beside the other ways, you could also use:
import sys
sys.stdout.write(f.readline())
Works with every Python version to date.
Rather than skipping the newline on output, you can strip it from the input:
print(line_number, f.readline().rstrip('\n'))
Related
This question already has answers here:
How to input a regex in string.replace?
(7 answers)
Closed 2 years ago.
I'm extremely new to coding and python so bear with me.
I want to remove all text that is in parenthesis from a text file. There are multiple sets of parenthesis with varying lengths of characters inside. From another similar post on here, I found
re.sub(r'\([^()]*\)', '', "sample.txt")
which is supposed to remove characters between () but does absolutely nothing. It runs but I get no error code.
I've also tried
intext = 'C:\\Users\\S--\\PycharmProjects\\pythonProject1\\sample.txt'
outtext = 'C:\\Users\\S--\\PycharmProjects\\pythonProject1\\EDITEDsample.txt'
with open("sample.txt", 'r') as f, open(outtext, 'w') as fo:
for line in f:
fo.write(line.replace('\(.*?\)', '').replace('(', " ").replace(')', " "))
which successfully removes the parenthesis but nothing inbetween them.
How do I get the characters between the parenthesis out?
EDIT: I was asked for a sample of sample.txt, these are it's contents:
Example sentence (first), end of sentence. Example Line (second), end
of sentence (end).
As you can see here, the function sub does not receive a filename as parameter, but actually it receives the text on which to work.
>>> re.sub(r'\([^()]*\)', '', "123(456)789")
'123789'
As for your second attempt, notice that string.replace does not take in REGEX expressions, only literal strings.
I have a question regarding printing in Python. I use the following for printing
I want to generate a bash script using python 3.7.
res="""\
{someline} some more code some keywords etc
""".format(someline = self.someline)
res = textwrap.dedent(res)
This I use for getting the text in a format that it autmatically prints newlines etc.
But if I now have in my string a lot of arguments, the line gets longer and longer. But if i press enter, I get a newline.
So is there a way to have a wordwrap without having a new line for better
readability in the code?
print("\
This will get printed\
, and this will be on the same line\
")
When using normal quotes, as in " or ', ending a line with a backslash then starting a new line will continue the string over to the next line and not create a new line, which is what you're looking for.
This code is from http://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions
with open("myfile.txt") as f:
for line in f:
print line,
What I don't understand is what's that , for at the end of print command.
I also checked doc, http://docs.python.org/2/library/functions.html#print.
Not understanding enough, is it a mistake?(it seems not. it's from the official tutorial).
I am from ruby/javascript and it's unusual for me.
In python 2.7, the comma is to show that the string will be printed on the same line
For example:
for i in xrange(10):
print i,
This will print
1 2 3 4 5 6 7 8 9
To do this in python 3 you would do this:
for i in xrange(10):
print(i,end=" ")
You will probably find this answer helpful
Printing horizontally in python
---- Edit ---
The documentation, http://docs.python.org/2/reference/simple_stmts.html#the-print-statement, says
A '\n' character is written at the end, unless the print statement ends with a comma.
It prevents the print from ending with a newline, allowing you to append a new print to the end of the line.
Python 3 changes this completely and the trailing comma is no longer accepted. You use the end parameter to change the line ending, setting it to a blank string to get the same effect.
From Python trailing comma after print executes next instruction:
In Python 2.x, a trailing , in a print statement prevents a new line to be emitted.
The standard output is line-buffered. So the "Hi" won't be printed before a new line is emitted.
in python 2.7:
print line,
in python 3.x:
print(line, end = ' ')
This question already has answers here:
How to search and replace text in a file?
(22 answers)
Closed 8 years ago.
I am trying to replace text in a text file (let's just call the file test.txt), here is the example text:
Math is good
Math is hard
Learn good math
be good at math
DO\SOMETHING\NOW
I want something like:
Math is good
Math is hard
Learn good science
be good at science
DO\SOMETHING\NOW
I am trying to use fileinput in the following way
import fileinput
file = fileinput.input("Path/To/File/text.txt", inplace=True)
for line in file:
print(line.replace("math", "science"))
The problem is that the print function automatically attaches "\n" so it skips a new line. I tried replacing with using "sys.stdout.write(line.replace("math", "science")) but that outputed numbers in the text file. So how do I do this efficiently so that I get the results I want. Should I just use open and go line by line and checking if the word "math" pops up and replace the word? Any help would be greatly appreciated!
You can tell print() not to write a newline by setting the end keyword argument to an empty string:
print(line.replace("math", "science"), end='')
The default value for end is '\n'.
Alternatively you could remove the newline from line:
print(line.rstrip('\n').replace("math", "science"))
This question already has answers here:
How can I remove a trailing newline?
(27 answers)
Closed 8 years ago.
I had a list that read from a text file into an array but now they all have "\n" on the end. Obviously you dont see it when you print it because it just takes a new line. I want to remove it because it is causing me some hassle.
database = open("database.txt", "r")
databaselist = database.readlines()
thats the code i used to read from the file. I am a total noob so please dont use crazy technical talk otherwise it will go straight over my head
"string with or without newline\n".rstrip('\n')
Using rstrip with \n avoids any unwanted side-effect except that it will remove multiple \n at the end, if present.
Otherwise, you need to use this less elegant function:
def rstrip1(s, c):
return s[:-1] if s[-1]==c else s
Use str.rstrip to remove the newline character at the end of each line:
databaselist = [line.rstrip("\n") for line in database.readlines()]
However, I recommend that you make three more changes to your code to improve efficiency:
Remove the call to readlines. Iterating over a file object yields its lines one at a time.
Remove the "r" argument to open since the function defaults to read-mode. This will not improve the speed of your code, but it will make it less redundant.
Most importantly, use a with-statement to open the file. This will ensure that it is closed automatically when you are done.
In all, the new code will look like this:
with open("database.txt") as database:
databaselist = [line.rstrip("\n") for line in database]