I have a list of counters
counters = ['76195087', '963301809', '830123644', '60989448', '0', '0', '76195087', '4006066839', '390361581', '101817210', '0', '0']
and I would like to create a string using some of these counters....
cmd = 'my_command' + counters[0:1]
But I find that I am unable to concatenate strings and lists.
What I must have at the end is a string that looks like this:
my_command 76195087
How do I get these numbers out of their list and get them to behave like strings?
You can join strings in a list with, well, join:
cmd = 'my_command' + ''.join(counters[:1])
But you shouldn't construct a command like that in the first place and give it to os.popen or os.system. Instead, use the subprocess module, which handles the internals (and escapes problematic values):
import subprocess
# You may want to set some options in the following line ...
p = subprocess.Popen(['my_command'] + counters[:1])
p.communicate()
If you just want a single element of the list, just index that element:
cmd = 'my_command ' + counters[0]
If you want to join several elements, use the 'join()' method of strings:
cmd = 'my_command ' + " ".join(counters[0:2]) # add spaces between elements
If you just want to append a single counter, you can use
"my_command " + counters[0]
or
"%s %s" % (command, counters[0])
where command is a variable containing the command as a string. If you want to append more than one counter, ' '.join() is your friend:
>>> ' '.join([command] + counters[:3])
'my_command 76195087 963301809 830123644'
You have to access an element of the list, not sublists of the list, like this:
cmd = 'my_command' + counters[0]
Since I guess you're interested in using all the counters at some point, use a variable to store the index you're currently using, and increment it where you see fit (possibly inside a loop)
idx = 0
cmd1 = 'my_command' + counters[idx]
idx += 1
cmd2 = 'my_command' + counters[idx]
Of course, being careful of not incrementing the index variable beyond the size of the list.
Related
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(',')
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) + ']')
I have a file which contains the list of filesnames:
List:
Sample1_R1_L1.bam
Sample1_R2_L1.bam
Sample2_R1_L1.bam
Sample2_R2_L1.bam
.......
I want to run a unix command that merges each pair of files:
$ samtools merge Sample1_merged_output.bam Sample1_R1_L1.bam Sample1_R2_L1.bam
I was thinking I can achieve this by using the for loop in python which takes two elements from the list of file names and runs the "subprocess" to call the unix command. I found a post which helped to access two elements at a time but I can not pass the names of the file to the unix shell:
for i,d in enumerate(list):
if i < (len(list) - 1):
print d + ' ' + list[i+1]
# print d + ' ' + list[i+1]
any suggestions to achieve this are welcome. Thanks.
You should use argv to get arguments.
from sys import argv
print argv[1]
Result will be:
merge
Then your code would be something like:
list2merge = argv[2:]
for i,d in enumerate(list2merge):
print str(i) + ' ' + str(d)
UPDATE
You should not use list as variable name, since it's reserved.
I pass mylist as an argument to be get after by sys.argv I do this:
mylist = str(list)
nbre = str(nbre)
comm = 'python2.6 file.py ' + mylist + ' ' + nbre + ' &'
os.system(comm)
In file.py, I am expected to get mylist by this way and which contains [machine1,machine2] but when doing:
mylist = sys.argv[1]
I get [machine1, which is wrong. When I display sys.argv I found:
['file.py','[machine1,','machine2]','1']
I didn't understand why my list is composed like that?
Apart from this being a terrible way to communicate a list from one python script to another, you'd need to use quotes around the list to prevent it from being split by the shell:
comm = 'python2.6 file.py "%s" "%s" &' % (mylist, nbre)
I've used string formatting to put the quotes around mylist and nbre.
You really want to look into the subprocess module to invoke other processes without the shell getting in the way.
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']