2

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
0

3 Answers 3

2

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

Comments

1

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.

3 Comments

thank you very much. it is almost what i wanted, but mystring returns 2 rows. Probably because of looping.
Could be your console size
:) - it was from this for i in list:
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.