3

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?

4 Answers 4

4

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()
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

3

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'

3 Comments

are the double quotes significant? when I use single quotes I get the following message: TypeError: cannot concatenate 'str' and 'list' objects
also... I will need to use several of the counters as arguments in the command. How do I bring in several counters? + counters[0] + counters[3], etc?
@TheWellington The double quotes are the same as single quotes, and I doubt you are using the exact code above.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.