Format string output - python

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(',')

Related

adding extra information to filename - python

I used the following line to rename my file by adding timing and remove extra space and replace it with (-)
if i would like to add extra information like lable before the timing ,
filename = ("%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
the current output looks like
testfile_2016-07-25_12:17:14.mp4
im looking to have the file output as
testfile_2016-07-25_12:17:14-MediaFile.mp4
try the following ,
filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S","Mediafile",time.localtime()))).replace(" ", "-")
what did i missed here ?
You're using the function strftime incorrectly. Strftime only takes 2 arguments and you're passing it 3.
You would need to generate the string from the time and apply some string operations to append the extra info.
If you want to add MediaFile to the end of the filename simply do something like this.
filename = ("%s_%s-MediaFile.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()))).replace(" ", "-")
filename = ("%s_%s-%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()), 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:29:28-MediaFile.mp4'
To understand better how this works and slightly improve readability, you can define your time stamp in a separate variable:
timestr = time.strftime("%Y-%m-%d_%H:%M:%S", time.localtime()) # 2016-07-25_10:31:03
filename = ("%s_%s-%s" %(pfile, timestr, 'MediaFile')).replace(' ', '-')
# 'testfile_2016-07-25_10:31:03-MediaFile.mp4'
or
filename = ("%s_%s-MediaFile.mp4" %(pfile, timestr)).replace(' ', '-')
For completeness, you can also use the format() method:
filename = '{0}_{1}-MediaFile.mp4'.format(pfile, timestr).replace(' ', '-')
What you are looking for should be :
filename = ("%s_%s_%s.mp4" %(pfile, time.strftime("%Y-%m-%d_%H:%M:%S",time.localtime()),"Mediafile")).replace(" ", "-")
In your original code, the 'Mediafile' string was not in the right place : you put it as an argument of strftime(), when you should put it as one of the string to replace, in the 2nd level of parentheses.

Python: For loop Concatenation

cat = "["
for row in res:
cat = cat + (str((row['weeks'])) + ',')
cat = (cat + "]").replace(',]', ']')
The above bit of code gives a result string as:
[30,31,32,33,34,35,36,37,38,39,40]
However what I want is:
[W30,W31,W32,W33,W34,W35,W36,W37,W38,W39,W40]
I have been unsuccessful in concatenating the W before each number. How could I do this?
This is the unsuccessful code that I tried:
cat = cat + (str('W'+ (row['weeks'])) + ',')
This gives the desired string:
cat = '[{}]'.format(','.join('W{}'.format(i) for i in row['weeks']))
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# this gives 'W30', 'W31', etc.
# ^^^^^^^^^
# this joins them with commas: 'W30,W31,...,W40'
# ^^^^^^^^^^^^^^
# this puts [ ] around
You have done this
cat = cat + (str('W'+ (row['weeks'])) + ',')
It should be
cat = cat + ('W'+ str(row['weeks']) + ',')
if you want it to be a list you could do this
cat = ["W"+str(row['weeks']) for row in res]
code:
cat = '[W' + ',W'.join(str(element) for element in row['weeks']) + ']'
Instead of getting an answer from here (since there are many ways to do it), you should understand what went wrong with your own code.
(str('W'+ (row['weeks'])) + ',')
What is the order of operations here?
We find row['weeks'].
We attempt 'W' + that.
We attempt str on that.
We attempt that + ','.
Presumably, row['weeks'] is an integer, so the addition with 'W' will fail. You must do this after applying str to the integer.
If you want a list made of strings do
cat = [ 'W'+str(row['weeks']) for row in res]
and, if you want a single string, turn the list into a string
string_cat = str(cat)
cat = "[" + ",".join('W' + str(row['weeks']) for row in res) + "]"
For each row in res convert row['weeks'] to string, prefix it with 'W', and join all such strings with the ',' character. Then just add opening [ and closing ].

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

Writing multiple values in a text file using python

I want to write mulitiple values in a text file using python.
I wrote the following line in my code:
text_file.write("sA" + str(chart_count) + ".Name = " + str(State_name.groups())[2:-3] + "\n")
Note: State_name.groups() is a regex captured word. So it is captured as a tuple and to remove the ( ) brackets from the tuple I have used string slicing.
Now the output comes as:
sA0.Name = GLASS_OPEN
No problem here
But I want the output to be like this:
sA0.Name = 'GLASS_HATCH_OPENED_PROTECTION_FCT'
I want the variable value to be enclosed inside the single quotes.
Does this work for you?
text_file.write("sA" + str(chart_count) + ".Name = '" + str(State_name.groups())[2:-3] + "'\n")
# ^single quote here and here^

concatenating string in python

I am converting a command line to a python string. The command line is:
../src/clus -INFILE=../input/tua40.sq -OUTPUT=OUT
The python statement is:
c_dir = '~/prj/clus/'
c_bin = c_dir + 'src/clus'
c_data = c_dir + 'input/tua40.sq'
c = LiveProcess()
c.executable = c_bin
c.cwd = c_dir
c.cmd = [c.executable] + ['-INFILE=', 'c_data, '-OUTPUT=OUT']
Problem is the c.cmd at the end looks like
~/prj/clus/src/clus -INFILE= ~/prj/clus/input/tua40.sq ...
Not that there is a 'space' after '=' which causes the program to report an error.
How can I concatenate '=' to the path?
LiveProcess is expecting an argv-style list of arguments. Where you want to make one argument, you need to provide one string. So use concatenation to make the string:
c.cmd = [c.executable] + ['-INFILE='+c_data, '-OUTPUT=OUT']
Also, no need for the list addition:
c.cmd = [c.executable, '-INFILE='+c_data, '-OUTPUT=OUT']
Why don't you just concatenate string like this:
a = 'A'+'B'
then
a == 'AB'
that is in your example
['-INFILE=' + c_data, '-OUTPUT=OUT']
Given that it looks like you're concatenating paths, you should be using os.path.join, not regular string concat.
Try this:
c.cmd = [c.executable] + ['-INFILE='+c_data, '-OUTPUT=OUT']

Categories