Below is the code:
data2 = [["jsdfgweykdfgwey",
"kdgwehogfdoyeo",
"ndlgyehwfgdiye",
"ndfluiwgmdfho"],
["---------------------------------------------------------------------------------",
"-------------------------------------------------------------------------------",
"------------------------------------------------------------------------------",
"-----------------------------------------------------------------------------"],
["kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt1",
"kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt2",
"kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt3",
"kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt4\
kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt4 \
kdglwduifgeuifeudiwfkjkedluefywduifkcjkewfgpt4"]]
data = [x for x in data2 if x is not None]
col_width = max(len(word) for row in data for word in row) + 2
for row in data:
print "".join(word.ljust(col_width) for word in row)#print in single line in output console.
It is not printing output properly
How to print output in single line in command output (OS Linux)
or any other suggestions to print in column wise for long line printing.
Each element in your list is printed out as a combined string as you wished. But by doing the word.ljust(col_width) step, where col_width is about 140, you are taking up a lot of empty space for printing. If your console size is small it will seem like you are printing in a new line. Try to replace col_width by 10, you will probably get the elements of data2[0] printed in one line.
If you want data2 to be printed as a single string then you can do the following:
tmp=''
for row in data:
a = " ".join(word.ljust(col_width) for word in row)
tmp = tmp + a
tmp will contain each element of data2 in a string one after the other
Related
This code prints a pattern of a series of asterisks, taking the params if the pattern is to be printed normally or inverted, and also requests the number of rows.
def print_pattern(rows):
row = 0
while row <= rows:
output = row * "*"
row += 1
print(output)
output = print_pattern(True, 3)
My expected output is this:
*
**
***
I instead get something like this, with an extra line on top
*
**
***
So why is this extra line left in the start?
You started row at 0, so your first loop iteration prints "*" 0 times, aka a blank line. I'd suggest starting row at 1.
I am trying to format the results of a query such that results are printed on their respective lines. For example, I am querying stores by store number and obtaining the location from a JSON file, but when printing, the store number and location are printing on separate lines:
Code Snippet: (Searching for stores 35 and 96)
for store, data in results.items():
print('Store: {}'.format(store))
if data:
for location in data:
print(location)
Current Output:
Store: 35
{'location': Iowa}
Store: 96
{'location': Minnesota}
Desired output (or something similar):
Store: 35, 'location': Iowa
Store: 96, 'location': Minnesota
Adding end='' to your first print statement should fix the problem. By specifying that the end character is an empty string you will override the default \n character (by default print statements end with a new line character).
for store, data in results.items():
print('Store: {}'.format(store), end='')
if data:
for location in data:
print(location)
We will only add end='' to the first print statement because we want the new line to print after you print out the location.
If you want to separate your prints with a , of course you would just add + ',' to your first print statement.
This will work right off the bat if you're using Python 3. If you're using Python 2.X you will have to add this line to the top of your file: from __future__ import print_function
Here's a simple example of this in action:
from __future__ import print_function
l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']
for i,j in zip(l1, l2):
print (i, end='')
print (j)
Output:
hello1world1
hello2world2
hello3world3
If we took the same code but altered it slightly and just removed the end='', this is what would happen:
from __future__ import print_function
l1 = ['hello1', 'hello2', 'hello3']
l2 = ['world1', 'world2', 'world3']
for i,j in zip(l1, l2):
print (i)
print (j)
Output:
hello1
world1
hello2
world2
hello3
world3
As you can see each line would end with a new line character, this printing a new line for each statement.
I would write all the output in a variable and print the variable only once at the end. This also allows you to save time (despite using more memory) since you need only a single access to the stdout. The code is also easier to follow (in my opinion):
output = ''
for store, data in results.items():
output += 'Store: {}'.format(store)
if data:
for location in data:
output += location+'\n'
# Only at the end you print your output
print(output)
You can also print at the end of each iteration (you still access half of the times to the stdout) with the following:
for store, data in results.items():
output = 'Store: {}'.format(store)
if data:
for location in data:
output += location+'\n'
# Print only at the end of the loop
print(output)
If you want a new line for each Store but not for each "location":
output = ''
for store, data in results.items():
output += 'Store: {}'.format(store)
if data:
for location in data:
output += location
output += '\n'
# Only at the end you print your output
print(output)
I think this approach is much more flexible, easier to read in the code and is also faster.
Hope to be helpful
I have a question regarding formatting. I am trying to extract relevant data and insert this data into a fortran file. Thankfully, I am using python to accomplish this task. It just so happens that the fortran file is sensitive to the number of spaces between text. So, this brings me to my question. My array array data looks like:
[[ -1.80251269 12.14048223 15.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
[[-14.80251269 1.14048223 1.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
[[ -0.80251269 0.14048223 0.47522331]
[ -2.63865822 13.1656285 15.97462801]
[ -1.76966256 11.35311123 16.13958474]
[ -0.76320052 12.45171386 15.34209158]
[ -2.12634889 11.84315415 14.48020468]]
These elements are floats, not strings. For example, I wanted the the first row (and every row thereafter) of the data to look like:
-1.80251269 12.14048223 15.47522331
How would I accomplish this? To be specific, there are 5 white spaces that seperate the left margin from the 1st number, -1.80251269, and 5 white spaces that seperate each of the three numbers. Notice also that I need the array brackets gone, but I suspect I can do this with a trim function. Sorry for my lack of knowledge guys; I do not even know how to begin this problem as my knowledge in Python syntax is limited. Any help or tips would be appreciated. Thanks!
EDIT: this is the code I am using to generate the array:
fo = np.genfromtxt("multlines.inp")
data=scipy.delete(fo, 0, 1)
txt = np.hsplit(data,3)
all_data = np.vsplit(data, 4)
i=0
num_molecules = int(raw_input("Enter the number of molecules: "))
print "List of unaltered coordinates:"
while i < (num_molecules):
print all_data[i]
If you are using NumPy, you can use np.savetxt:
np.savetxt('a.txt', a.reshape(15,3), '%16.8f')
To get
-1.80251269 12.14048223 15.47522331
-2.63865822 13.16562850 15.97462801
-1.76966256 11.35311123 16.13958474
...
(You need to reshape your array into 2-dimensions to do what I think you want).
If you have your data formatted as a list, then I suspect that #kamik423's answer will help you. If it if formatted as a string, you may wish to try something like the following.
def properly_format(line):
nums = line.strip(' []\t').split()
spaces = ' '
return spaces + nums[0] + spaces + nums[1] + spaces + nums[2]
lines = my_array_string.splitlines() #if your data is a multiline string
for line in lines:
formatted_line = properly_format(line)
# do something with formatted_line
Edit: forgot to split the string.
If you don't care about the length of each block you can just do
for i in whateverYouArrayIsCalled:
print str(i[0]) + " " + str(i[1]) + " " + str(i[2])
if you however want to have all the elements to be inline try
for i in whateverYouArrayIsCalled:
print (str(i[0]) + " ")[:20] + (str(i[1]) + " ")[:20] + str(i[2])
where the 20 is the length of each block
(for 2.7)
I will assume that the data array is saved in a data.txt file and you want to save the result into fortran.txt, then:
fortran_file = open('fortran.txt','w') # Open fortran.txt for writing
with open('data.txt',r) as data_file: #Open data.txt for reading
while True:
line = data_file.readline()
if not line: break # EOF
result = line.strip('[]').split()
result = " " + " ".join(result)
fortran_file.write(result)
fortran_file.close()
try this:
import numpy
numpy.set_printoptions(sign=' ')
I'm using Python 3 and I need to parse a line like this
-1 0 1 0 , -1 0 0 1
I want to split this into two lists using Fraction so that I can also parse entries like
1/2 17/12 , 1 0 1 1
My program uses a structure like this
from sys import stdin
...
functions'n'stuff
...
for line in stdin:
and I'm trying to do
for line in stdin:
X = [str(elem) for elem in line.split(" , ")]
num = [Fraction(elem) for elem in X[0].split()]
den = [Fraction(elem) for elem in X[1].split()]
but all I get is a list index out of range error: den = [Fraction(elem) for elem in X[1].split()]
IndexError: list index out of range
I don't get it. I get a string from line. I split that string into two strings at " , " and should get one list X containing two strings. These I split at the whitespace into two separate lists while converting each element into Fraction. What am I missing?
I also tried adding X[-1] = X[-1].strip() to get rid of \n that I get from ending the line.
The problem is that your file has a line without a " , " in it, so the split doesn't return 2 elements.
I'd use split(',') instead, and then use strip to remove the leading and trailing blanks. Note that str(...) is redundant, split already returns strings.
X = [elem.strip() for elem in line.split(",")]
You might also have a blank line at the end of the file, which would still only produce one result for split, so you should have a way to handle that case.
With valid input, your code actually works.
You probably get an invalid line, with too much space or even an empty line or so. So first thing inside the loop, print line. Then you know what's going on, you can see right above the error message what the problematic line was.
Or maybe you're not using stdin right. Write the input lines in a file, make sure you only have valid lines (especially no empty lines). Then feed it into your script:
python myscript.py < test.txt
How about this one:
pairs = [line.split(",") for line in stdin]
num = [fraction(elem[0]) for elem in pairs if len(elem) == 2]
den = [fraction(elem[1]) for elem in pairs if len(elem) == 2]
I've got a for loop set up to read in an X and Y values from a .csv, so far so good.
However, the .csv is 65,000 rows long! and about 2000 of these are just blank rows.
How do I tell the for loop to ignore / skip blank rows and just get the next set of values?
I've been try to use 'continue' like this...
for line in lines:
#split the content of each line to an array delimited by a comma ,
pos = [x.strip() for x in line.split(',')]
if pos == "":
continue
else:
#set up variables
x = float(pos[0])*10000
y = float(pos[1])*10000
z = 0.0
But it doesn't work, whenever it gets to the first blank row it just adds zeros for the rest and I get this error message...
ValueError: empty string for float()
I did try removing the blank rows in Apple Numbers before Python imports them, but apparently something as simple as removing blank rows is a total ball-ache in Numbers.
I also tried to strip out all the blank variables before the For Loop, but couldn't get that to work either.
Any pointers would be greatly appreciated, but please keep it simple! (I'm new to this stuff and the more esoteric code goes right over my head).
In the equality check pos is no longer a string it is a list.
So you can check if the line itself is empty:
for line in lines:
if line.strip() == "":
continue
#split the content of each line to an array delimited by a comma ,
pos = [x.strip() for x in line.split(',') if x.strip()]
# make sure you have x and y
if len(pos) < 2:
continue
#set up variables
x = float(pos[0])*10000
y = float(pos[1])*10000
z = 0.0
By adding the if condition while defining pos, we now discard empty elements.
I am newbie for python , but I think you could try the code below.
My thought is If there is a empty line, the length of line should be 0. Thank you
if not line:
continue
From the exception: ValueError: empty string for float() I infer that "blank rows" mean something like '1, ,' in your case i.e., you get an error if any of the (first two) fields in a row is blank (contain only whitespace):
for line in lines:
try:
x, y = map(float, line.split(',')[:2])
except ValueError:
continue # skip invalid (for whatever reason) lines
else:
# use x, y here
x *= 10000
y *= 10000
z = 0.0
print(x, y, z)
Example
1,2
# the next line is blank AND IT IS SUCCESSFULLY SKIPPED NO 0,0
# missing second field
70,
# both empty
,
# first empty
,0
#
,,80,90
3,4
Output
(10000.0, 20000.0, 0.0)
(30000.0, 40000.0, 0.0)