Stefan
Stefan

Reputation: 33

python assign print output to a variable

I have a list of strings which has below elements. This list can have 1,2, or more elements.

list=['abc', 'xyz']

I want to use them and create a one line string like below and use it later in some other string concatenations (creating a command):

Move abc to folder c:\data, move xyz to folder c:\data

Until now I have managed to print them with:

for i in list:
  print("Move '" + i + "' to folder 'C:\DATA'",end=", ")

output is:

Move 'xyz' to folder 'c:\DATA', Move 'xyz' to folder 'c:\DATA',

I want to remove the last comma and if possible to assign this output to a variable. Finally the scope is to generate and execute a command (using subprocess module) like this:

restore database db move 'xyz' to folder 'c:\data', Move 'xyz' to folder 'c:\DATA' -server servername -instance instance_name

Upvotes: 2

Views: 949

Answers (3)

Mad Physicist
Mad Physicist

Reputation: 114310

When you print something, it's a one-shot thing. The string you made for printing is gone once it's shown on the console1. Instead you are probably going to want to build a string with your formatted data in memory, and then print it, or do something else.

String's join method will allow you to insert commas only between elements. The format method will allow you to format the individual elements with custom data:

mystring = ", ".join("Move '{}' to folder 'C:\\DATA'".format(i) for i in mylist)

Now you have a string that you can print, concatenate, split, pass to a subprocess, etc...


1 you can print to an in-memory file and extract the output that way, but we won't go into that now.

Upvotes: 1

caverac
caverac

Reputation: 1637

You can do this via the join function in Python.

>>> lst = ['abc', 'xyz']
>>> s = ', '.join([r'Move {} to folder c:\data'.format(f) for f in lst])
>>> print(s)
Move abc to folder c:\data, Move xyz to folder c:\data

Upvotes: 2

fixatd
fixatd

Reputation: 1404

You can use join for that:

list=['abc', 'xyz']
print(", ".join([ "Move '{0}' to folder 'c:\{0}'".format(item) for item in list]))

# Move abc to folder c:\abc, Move xyz to folder c:\xyz

Upvotes: 1

Related Questions