I have a list that contains logs, and I am trying to add an empty line between specific blocks. So when I get to the end of a specific block, I can see a bit of separation, instead of looking like a continuous list.
EX:
log a:
kdsaldklsadkaslk
kasldkasldkasldkasldk
log a1:
lkpadkfaldkfdsl
klsdkfldskfsdl
So far I've tried all that I was able to find online, but I was unsuccessful. Either I am forced to add anything but an empty line (like a sequence of ----- for example), or the space added will be added to every single line (which is not what I want).
If I add in the list the empty line, like
log_list.append(" \n")
when I print the list using
print "\n".join(log_list)
all the empty lines that I have added are not printed.
But if I add any character to the append command, then it will be printed.
Is there any option that is automatically taking off the empty lines in a list, when I do the join command? Otherwise I do not understand why I cannot have an empty line in the list.
Is there another way to print out lists? I've always seen printing lists with the join command (all my objects in the list are strings).
Thanks!
For me, this works (showing that there is no monkey business with appending a \n and then joining with a \n):
>>> log_list = ['a']
>>> log_list.append('\n')
>>> log_list.append('b')
>>> log_list.append('c')
>>> print '\n'.join(log_list)
a
b
c
What did you do differently?
If the list is already created, you can for example insert a blank line before every line ending with ":" like this
print "\n".join("\n"+s if s.endswith(":") else s for s in log_list)
It's probably clearer to just use a loop though
for s in log_list:
if s.endswith(":"):
print
print s
You can change the condition to suit your requirements, eg s.startswith("log ")
Related
I have to print something by taking input from a file. The first few lines are empty. Therefore the output is turning out to be empty. It's like someone has pressed enter key 10 times before writing anything.
I want to ignore those inputs and consider only those which are not empty. What should I do?
By checking if there is anything apart from a newline character ("\n")is present in a line, your problem can be solved
fileObj=open(Filename)
for row in fileObj:
if len(row.replace("\n",""))>0:
print (row)
#Do your operations
If you can edit your question to add material, that would be helpful, but here’s a few pointers for now.
Assuming you’re taking the file in as a string (let’s call it "f"), you can loop over empty lines with a while loop:
charN = 0
while f[charN] == “\n”:
f = f[1:]
This allows you to chop off only the initial returns while keeping any line breaks later on in the file.
Note that, depending on the system this was written in, the enters may be stored as “\r\n”, in which case you could easily alter this for loop to remove those characters too. Good luck!
I've settled on a text-file based save system for my game, storing the values of required variables with keywords - for example, the password that tells the game which chapter to play. However, it appears to be malfunctioning, and I can't see why.
Before starting the game, we have:
if not os.file.isfile('TSGsave{0}.txt'.format(name)):
TSGsave=open('TSGsave{0}.txt'.format(name),'wt')
TSGsave.write('\nw5CT$n<jfW=-#J%4Ya5##')
TSGsave.close()
(the keyword used is a bunch of jibberish so that the user can't change it knowing what's going to happen). This adds w5CT$n<jfW=-#J%4Ya5## to the text file. We then have:
for i in range (len(lines)):
if 'w5CT$n<jfW' in lines[i]:
findpass=lines[i]
for i in range (len(findpass)):
if findpass[i]=='=':
cutfrom=i+1
password=findpass[cutfrom:len(findpass)]
to retrieve the variable (which can change, so it can't be written in as definite value). I know it works, because I added print (password) to the code and it returned -#J%4Ya5##. Then to start the corresponding chapter, the code is:
if password=='-#J%4Ya5##':
but it isn't starting the indented block. In the shell, the program ends and goes back to the >>> line.
If there is a way to fix this code, great - but another code to do the same thing would work just as well.
Your lines contain newlines, and these are being included. Strip these from the line:
findpass = lines[i].rstrip('\n')
Printing a value with a newline in it will simply add an extra black line after the print. Always use the repr() function to produce a Python representation of strings to see such characters:
>>> print '-#J%4Ya5##\n'
-#J%4Ya5##
>>> print repr('-#J%4Ya5##\n')
'-#J%4Ya5##\n'
Your parsing code is overly complicated; you can use str.split() or str.partition() to split your password from the line instead. You should just loop over the lines list directly rather than produce indices with range():
for line in lines:
if 'w5CT$n<jfW' in line:
password = line.partition('=')[2].rstrip('\n')
Basically I have a text file, I am reading it line by line. I want to merge some lines together (a part of the text) in to a single string and add it as an element to a list.
These parts of the text that I want to combine start with the letters "gi" and end with ">". I can successfully isolate this part of the text but I am having trouble manipulating with it in any way, i would like it to be a single variable, acting like a individual entity. So far it is only adding single lines to the list.
def lines(File):
dataFile = open(File)
list =[]
for letters in dataFile:
start = letters.find("gi") + 2
end = letters.find(">", start)
unit = letters[start:end]
list.append(unit)
return list
This is an example:
https://www.dropbox.com/s/1cwv2spfcpp0q0s/pythonmafft.txt?dl=0
So every entry that is in the file I would like to manipulate as a single string and be able to append it to a list. Every entry is seperated by a few empty lines.
First off, don't use list as a variable name. list is a builtin and you override it each time you assign the same name elsewhere in your code. Try to use more descriptive names in general and you'll easily avoid this pitfall.
There is an easier way to do what you're asking, since '>gi' (in the example you gave) is placed together. You can simply use split and it'll give you the units (without '>gi').
def lines(File):
dataFile = open(File)
wordlist = dataFile.read().split('>gi')
return wordlist
I am trying to convert a multiline string to a single list which should be possible using splitlines() but for some reason it continues to convert each line into a list instead of processing all the lines at once. I tried to do it out of the for loop but doesnt seem to have any effect. I need the lines as a single list to use it another function. Below is how I get the multiline into a single variable. What am I missing???
multiline_string_final = []
for match_multiline in re.finditer(r'(^(\w+):\sThis particular string\s*|This particular string\s*)\{\s(\w+)\s\{(.*?)\}', string, re.DOTALL):
multi_line_string = match_multiline.group(4)
print multiline_string
This last print statement prints out the strings like this:
blah=0; blah_blah=1; Foo=3;
blah=4; blah_blah=5; Foo=0;
However I need:
['blah=0; blah_blah=1; Foo=3;''blah=4; blah_blah=5; Foo=0;']
I understand it has to be something with the finditer but cant seem to rectify.
Your new problem also has nothing to do with finditer. (Also, your code is still not an MCVE, you still haven't shown us the sample input data, etc., making it harder to help you.)
From this desired output:
['blah=0; blah_blah=1; Foo=3;''blah=4; blah_blah=5; Foo=0;']
I'm pretty sure what you're looking for is to get a list of the matches, instead of printing out each match on its own. That isn't a valid list, because it's missing the comma between the elements,* but I'll assume that's a typo from you making up data instead of building an MCVE and copying and pasting the real output.
Anyway, to get a list, you have to build a list. Printing things to the screen doesn't build anything. So, try this:
multiline_string_final.append(multiline_string)
Then, at the end—not inside the loop, only after the loop has finished—you can print that out:
print multiline_string_final
And it'll look like this:
['blah=0; blah_blah=1; Foo=3;',
'blah=4; blah_blah=5; Foo=0;']
* Actually, it is a valid list, because adjacent strings get concatenated… but it's not the string you wanted, and not a format Python would ever print out for you.
The problem has nothing to do with the finditer, it's that you're doing the wrong thing:
for line in multiline_string:
print multiline_string.splitlines()
If multiline_string really is a multiline string, then for line in multiline_string will iterate over the characters of that string.
Then, within the loop, you completely ignore line anyway, and instead print multiline_string.splitlines()).
So, if multiline_string is this:
abc
def
Then you'll print ['abc\n', 'def\n'] 8 times in a row. That's not what you want (or what you described).
What you want to do is:
split the string into lines
loop over those lines, not over the original un-split string
print each line, not the whole thing
So:
for line in multiline_string.splitlines():
print line
I have 2 lists of strings, they are constructed from database content but I have difficulty in reading it into a txt file
list_a={u'XYZ-123-456',u'XYZ-123-456',u'XYZ-789-456',....}
list_b={u'Tom \n is creative', u'Sky is blue',....}
What I need to do is get rid of 'u' at the beginning of each string in both lists, getting rid of \n within each string in list_b where applicable.
then write each element in list_b to a text file, one by a line, into the txt file, whose title is the element in list_a. Strings with the same title should be in the same txt file. Anyone can help ?
I think I can use pop function to get rid of u, but how about the '\n' within the string?
I am also not 100% sure about the I/O function. Anyone can help me out with the sample script?
Thanks a lot, a newbie of python
Welcome so SO.
list_a is actually a set. The {} indicates set, which is a list of unique items - so you may not want this type if you expect multiple values in the 'list'. If you want an actual list then encapsulate the 'list' with [...] instead of {...}
The 'u' in the set indicates the text is unicode. if you want this removed:
list_a = map(str, list_a)
\n is a control character indicating a new line. This will be represented as a new line when printed in the console. If you really don't want new lines then do:
list_b= { item.replace('\n','') for item in list_b }
I assume you want each item on a new line in the text file. If so:
with open('c:\file.txt', 'w') as file:
file.write('\n'.join(list_a))
file.write('\n'.join(list_b))
for non duplicates merge the 2 lists into a set. As they are currently already sets this will work:
with open('c:\file.txt', 'w') as file:
file.write('\n'.join(list_a + list_b))