ANSWERED (But if for some reason you want to read it you can)
I am a beginner at Python and I know how to type the correct syntax but when I repeat it, it comes out with no extra lines, it just says "\n"
DETAILS ON EXAMPLE BELOW:
My variable is fred and I set it to what it says below, and then on the 3rd line I made it print the text.
Please tell me if I didn't describe it correctly, keep in mind I'm a beginner.
EXAMPLE:
>>> fred = '''How do dinosaurs pay their bills?
With tyrannosaurus checks!'''
>>> fred
'How do dinosaurs pay their bills?\nWith tyrannosaurus checks!'
The \n in that string represents the new line symbol. For pretty much all purposes, it is a new line.
What you're doing is correct.
To print the lines on separate lines:
for line in jack.split("\n"):
print(line)
Related
I know there are a lot of questions about file.read() but I dont think any of them answer this....
Can someone tell me why, if I read a file with say 12 lines, in the interpreter and print it by just typing in filename.read(), it is presented on one continuous line with the EOL character to signify each line?
Then, if I do the same but create define an object, say file-output = filename.read(), and then print that object, it then prints out as it appears in the file?
Does what I said make sense????
Many thanks
Looking at solutions to reading in a file in Python, every time the newline character should be stripped off:
In [5]: [line for line in open("text.txt", "r")]
Out[5]: ['line1\n', 'line2']
The intuitive behavior (judging by the popularity of some questions (1, 2) about this) would be to just yield the stripped lines.
What is the rationale behind this?
Well, this is a line. A line is defined by ending with the character \n. If a sequence of characters did not end with a \n (or EOF) how could we know it was a line?
"hello world"
"hello world\n"
The first is not a line, if we print it twice we might get
hello worldhello world
Wile the second version will give us
hello world
hello world
Migrating the asker's response/solution from the question to an answer:
Granted: 'intuitive' is subjective. 'Consistent', however, is less so. Apparently the 'line' concept in "line1\nline2".splitlines() is a different one than the one handled by the iter(open("text.txt")):
>>> assert(open("text.txt").readlines() == \
... open("text.txt").read().splitlines())
AssertionError
Pretty sure people do get caught by this.
So I was mistaken: maybe my intuition is just in line with the splitlines interpretation: the split stuff should not include the separators. Maybe the answer to my question is not technical, but more like "since PEP-xyz was approved by different people than PEP-qrs". Maybe I should post it to some python language forum.
It's worth leaving here that this is my second day in Python and I'm not very pro at this language. Any low level suggestion and easy to understand would be much appreciate.
I would like to use a variable inside a regex in python. I have read this question How to use a variable inside a regular expression? without any luck in the answer.
Code:
import time
import re
dia = time.strftime('%b %d')
final = open('/root/final.txt', 'ab')
file = open('/var/log/syslog', 'rb')
for line in file:
if re.findall('kernel|\bNetworkManager\b', line):
if re.findall(r'dia', line):
final.write(line)
There's a lot of code that I don't think is relevant to the question.
I have tried this solution as well if re.findall(r'%s'%dia, line) with no lucky.
Since I'm in here i would like to explain my thought and see if I'm in the right direction:
Open syslog
Look for the word kernel and NetworkManager
If the beginning of the line is today write to final.
Thanks in advance. Wish you a great year.
You can't reference a variable in a string. A string is just text, it has no knowledge of the namespace, and the interpreter does not resolve that for it.
Since your variable dia is a string, you can just use that in your call to re.findall:
if re.findall(dia, line):
pass
or something similar:
if re.findall(r"{0}".format(dia), line):
pass
As for that correctness of what you're doing, if format of the time stamp on the log is the same what you're using, it should be correct.
EDIT: if you are reading strings from the log, you need not (or shouldn't) open them as binary, i.e. the b flag
This might be a silly question but I'd like to know how other people handle this or if there's a standard/recommended way of going about it.
Below are two approaches to splitting a long text line when printing it to screen in python. Which one should be used?
Option 1
if some_condition: # Senseless indenting.
if another condition: # Senseless indenting.
print 'This is a very long line of text that goes beyond the 80\n\
character limit.'
Option 2
if some_condition: # Senseless indenting.
if another condition: # Senseless indenting.
print 'This is a very long line of text that goes beyond the 80'
print 'character limit.'
I personally find Option 1 ugly but Option 2 seems like it would go against the pythonic way of keeping things simple by using a second print call.
One way to do it can be with parenthesis:
print ('This is a very long line of text that goes beyond the 80\n'
'character limit.')
Of course, there are several ways of doing it. Another way (as suggested in comments) is the triple quote:
print '''This is a very long line of text that goes beyond the 80
character limit.'''
Personally I don't like that one much because it seems like breaking the indentation, but that's just me.
If you have a long string and want to insert line breaks at appropriate points, the textwrap module provides functionality to do just that. Ex:
import textwrap
def format_long_string(long_string):
wrapper = textwrap.TextWrapper()
wrapper.width = 80
return wrapper.fill(long_string)
long_string = ('This is a really long string that is raw and unformatted '
'that may need to be broken up into little bits')
print format_long_string(long_string)
This results in the following being printed:
This is a really long string that is raw and unformatted that may need to be
broken up into little bits
I need some help;
I'm trying to program a sort of command prompt with python
I need to split a text file into lines then split them into strings
example :
splitting
command1 var1 var2;
command2 (blah, bleh);
command3 blah (b bleh);
command4 var1(blah b(bleh * var2));
into :
line1=['command1','var1','var2']
line2=['command2']
line2_sub1=['blah','bleh']
line3=['blah']
line3_sub1=['b','bleh']
line4=['command4']
line4_sub1=['blah','b']
line4_sub2=['bleh','var2']
line4_sub2_operand=['*']
Would that be possible at all?
If so could some one explain how or give me a piece of code that would do it?
Thanks a lot,
It's been pointed out, that there appears to be no reasoning to your language. All I can do is point you to pyparsing, which is what I would use if I were solving a problem similar to this, here is a pyparsing example for the python language.
Like everyone else is saying, your language is confusingly designed and you probably need to simplify it. But I'm going to give you what you're looking for and let you figure that out the hard way.
The standard python file object (returned by open()) is an iterator of lines, and the split() method of the python string class splits a string into a list of substrings. So you'll probably want to start with something like:
for line in command_file
words = line.split(' ')
http://docs.python.org/3/library/string.html
you could use this code to read the file line by line and split it by spaces between words.
a= True
f = open(filename)
while a:
nextline=f.readline()
wordlist= nextline.split("")
print(wordlist)
if nextline=="\n":
a= False
What you're talking about is writing a simple programming language. It's not extraordinarily difficult if you know what you're doing, but it is the sort of thing most people take a full semester class to learn. The fact that you've got multiple different types of lexical units with what looks to be a non-trivial, recursive syntax means that you'll need a scanner and a parser. If you really want to teach yourself to do this, this might not be a bad place to start.
If you simplify your grammar such that each command only has a fixed number of arguments, you can probably get away with using regular expressions to represent the syntax of your individual commands.
Give it a shot. Just don't expect it to all work itself out overnight.