Python write output separated by semi-colon - python

I'm new to Python and I'm trying to output fields to a text file. I've been able to throw the output to a text file but it's got "[" and "]" bracketing each row and is separated by commas.
I don't want the enclosing brackets and I have a date field that contains a comma so I need the fields to be separated by semi-colons.
Here's an example of the code that I'm using:
f=open("output.txt","a+")
for item in x['data']:
print "Variable 1: " + str(var1)
print "Variable 2: " + str(var2)
a=str(var1.strip())
b=str(var2.strip())
row = "%s\n" % [a,b]
f.write(row)
My output looks like this:
['var1', 'var2']
I want it to look like this:
'var1'; 'var2'
Any help would be greatly appreciated.

If you want them wrapped in single quotes, 'var1'; 'var2', then use any of
row = "; ".join(repr(x) for x in [a, b])
or
row = "%r; %r" % (a, b)
or
row = "{!r}; {!r}".format(a, b)

Related

Format string output

With this python's code I may read all tickers in the tickers.txt file:
fh = open("tickers.txt")
tickers_list = fh.read()
print(tickers_list)
The output that I obtain is this:
A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI,
Neverthless, I'd like to obtain as ouput a ticker string exactly formatted in this manner:
["A2A.MI", "AMP.MI", "ATL.MI", "AZM.MI", ...]
Any idea?
Thanks in advance.
If you want the output to look in that format you want, you would need to do the following:
tickers_list= "A2A.MI, AMP.MI, ATL.MI, AZM.MI, BGN.MI, BMED.MI, BAMI.MI"
print("["+"".join(['"' + s + '",' for s in tickers_list.split(",")])[:-1]+"]")
With the output:
["A2A.MI"," AMP.MI"," ATL.MI"," AZM.MI"," BGN.MI"," BMED.MI"," BAMI.MI"]
Code explanation:
['"' + s + '",' for s in tickers_list.split(",")]
Creates a list of strings that contain each individual value, with the brackets as well as the comma.
"".join(...)[:-1]
Joins the list of strings into one string, removing the last character which is the extra comma
"["+..+"]"
adds the closing brackets
Another alternative is to simple use:
print(tickers_list.split(","))
However, the output will be slightly different as in:
['A2A.MI', ' AMP.MI', ' ATL.MI', ' AZM.MI', ' BGN.MI', ' BMED.MI', ' BAMI.MI']
Having ' instead of "
A solution for that however is this:
z = str(tickers_list.split(","))
z = z.replace("'",'"')
print(z)
Having the correct output, by replacing that character
you can to use Split function:
tickers_list = fh.read().split(',')

Removing Single Quotes from a String Stored in an Array

I wrote code to append a json response into a list for some API work I am doing, but it stores the single quotes around the alphanumerical value I desire. I would like to get rid of the single quotes. Here is what I have so far:
i = 0
deviceID = []
while i < deviceCount:
deviceID.append(devicesRanOn['resources'][i])
deviceID[i] = re.sub('[\W_]', '', deviceID[i])
i += 1
if i >= deviceCount:
break
if (deviceCount == 1):
print ('Device ID: ', deviceID)
elif (deviceCount > 1):
print ('Device IDs: ', deviceID)
the desired input should look like this:
input Device IDs:
['14*************************00b29', '58*************************c3df4']
Output:
['14*************************00b29', '58*************************c3df4']
Desired Output:
[14*************************00b29, 58*************************c3df4]
As you can see, I am trying to use RegEx to filter non Alphanumeric and replace those with nothing. It is not giving me an error nor is it preforming the actions I am looking for. Does anyone have a recommendation on how to fix this?
Thank you,
xOm3ga
You won't be able to use the default print. You'll need to use your own means of making a representation for the list. But this is easy with string formatting.
'[' + ', '.join(f'{id!s}' for id in ids) + ']'
The f'{id:!s} is an f-string which formats the variable id using it's __str__ method. If you're on a version pre-3.6 which doesn't use f-strings, you can also use
'%s' % id
'{!s}'.format(id)
PS:
You can simplify you're code significantly by using a list comprehension and custom formatting instead of regexes.
ids = [device for device in devicesRanOn['resources'][:deviceCount]]
if deviceCount == 1:
label = 'Device ID:'
elif deviceCount > 1:
label = 'Device IDs:'
print(label, '[' + ', '.join(f'{id!s}' for id in ids) + ']')

How to print output in single line in linux terminal

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

how to join various bits of string and data together using python

Python newbie here. I've been working my way through this code to basically create a string which includes a date. I have bits of the code working to get the data I want, however I need help formatting to string to tie in the data together.
This is what I have so far:
def get_rectype_count(filename, rectype):
return int(subprocess.check_output('''zcat %s | '''
'''awk 'BEGIN {FS=";"};{print $6}' | '''
'''grep -i %r | wc -l''' %
(filename, rectype), shell=True))
str = "MY VALUES ("
rectypes = 'click', 'bounce'
for myfilename in glob.iglob('*.gz'):
#print (rectypes)
print str.join(rectypes)
print (timestr)
print([get_rectype_count(myfilename, rectype)
for rectype in rectypes])
My output looks like this:
clickMY VALUES (bounce
'2015-07-01'
[222, 0]
I'm trying to create this output file:
MY VALUES ('2015-07-01', click, 222)
MY VALUES ('2015-07-01', bounce, 0)
When you call join on a string it joins together everything in the sequence passed to it, using itself as the separator.
>>> '123'.join(['click', 'bounce'])
click123bounce
Python supports formatting strings using replacement fields:
>>> values = "MY VALUES ('{date}', {rec}, {rec_count})"
>>> values.format(date='2015-07-01', rec='click', rec_count=222)
"MY VALUES ('2015-07-01', click, 222)"
With your code:
for myfilename in glob.iglob('*.gz'):
for rec in rectypes:
rec_count = get_rectype_count(myfilename, rec)
print values.format(date=timestr, rec=rec, rec_count=rec_count)
edit:
If you want to use join, you can join a newline, \n:
>>> print '\n'.join(['line1', 'line2'])
line1
line2
Putting it together:
print '\n'.join(values.format(date=timestr,
rec=rec,
rec_count=get_rectype_count(filename, rec))
for filename in glob.iglob('*.gz')
for rec in rectypes)
try this:
str1 = "MY VALUES ("
rectypes = ['click', 'bounce']
K=[]
for myfilename in glob.iglob('*.gz'):
#print (rectypes)
#print str.join(rectypes)
#print (timestr)
k=([get_rectype_count(myfilename, rectype)
for rectype in rectypes])
for i in range(0,len(rectypes)):
print str1+str(timestr)+","+rectypes[i]+","+str(k[i])+")"

Python formatting: How to insert blank spaces in between array data elements of data type float

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=' ')

Categories