0

How can I make a string dynamic based on any number of parameters?

In particular this return string:

return '{0} {1} {2} "{3} {4} {5} {6}"'.format(params[0], params[1], params[2], params[3], params[4], params[5], params[6])

It needs to be able to handle between 4 and 7 parameters in between the quotes, when I added {7} and params[7] I get an IndexError if there were only 4 parameters for the quotes (7 total parameters).

TIA

3 Answers 3

1
print '{0} "{1}"'.format(' '.join(params[:3]), ' '.join(params[3:]))

But I would advise you to not try to stick this in oneliner. Make two disctinct parts separately and then assemble then in via .format. This is going to be much more readable (even variable names document your code) and easier to maintain later.

One way to do this is to use dictionary:

data = {
    'first_part' : ' '.join(params[:3]),
    'quoted_part': ' '.join(params[3:])
}
print '{first_part} "{quoted_part}"'.format(**data)

This works well if you want to print this stuff on the screen etc. Just remember, that this is not a secure way to assemble shell commands or database queries!

2
  • @SamRoberts What do you mean by being able to do it in 2 lines?
    – RedX
    Nov 23, 2014 at 10:29
  • more verbose example added. I don't know what is the meanining of data in your code, but you should rather use something more descriptive that quoted_part etc. Also, if answer fits you, you should accept it, so other know it solves your problem.
    – m.wasowski
    Nov 24, 2014 at 0:19
0
str = '{} {} {} " ' + '{} '*(len(params)-3) +'"'
return str.format(*params)

Updated without the additional space at the end:

str = '{} {} {} "'  + ' '.join(['{}']*(len(params)-3)) +'"'
return str.format(*params)

>>>params=[1,2,3,4,5,6,7]

Output

'1 2 3 "4 5 6 7"'

The ' '.join(['{}']*(len(params)-3)) creates a string of '{}' and the len(params)-3 decides how many they are.

*params means a collection of arguments. Here it will unpack the params into a collection of arguments. param[0] is the first argument, param[1] is the second argument.... Then they will fill those {} with its value.

3
  • this produces an additional space before the second doublequote. Use ' '.join to avoid it.
    – m.wasowski
    Nov 23, 2014 at 1:10
  • An explanation about what this code does and how does it work ?
    – user2629998
    Nov 23, 2014 at 1:28
  • Thanks, but its giving this error: zero length field name in format Nov 23, 2014 at 1:36
0

The following seems a bit simplistic but works:

#!/bin/python
params = [1, 2, 3]
mystr = '%s ' * len(params) % tuple(params)

... though it does have a trailing space. To get rid of that you could use something a bit uglier like:

mystr = ('%s ' * (len(params)-1) + "%s") % tuple(params)

This assumes that old fashioned % interpolation is sufficient and that you don't need any special features provided by the .format() method.

1
  • I suppose I should mention that you could build a "template" string of any length less than the length of params and use a slice to supply just the desired sub-sequence of its items. That should be obvious; and it's not clear if that would be necessary for your use-cases.
    – Jim Dennis
    Nov 23, 2014 at 10:46

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.