1

I have a list of string with variable length. I do know that the minimum length of the list is 4. How do I print the list in the following format if the list grows to more than 4?

>>> strlist = ['a', 'b', 'c', 'd', 'f', 'g'] # Unknown length
>>> print ('%s %s %s %s' % (strlist [2], strlist [0], strlist [4], strlist [5]))

c a f g

If the list expands to

[..., 'h', 'i', 'j']

then I want the output to be

c a f g h i j

Obviously, I can't put 500 "%s" in my print function if the list expands so I'm hoping there's a better way.

3
  • You are printing the list elements in random order, is it intentional? Commented Nov 3, 2015 at 19:21
  • print('%s %s %s' % (strlist[2], strlist[0], ' '.join(strlist[4:])))? Commented Nov 3, 2015 at 19:22
  • In Python % is an operator for constructing strings -- not really anything to do with print per se. If for a given application % isn't adequate for getting the string that you want -- construct the string some other way and then print it. Commented Nov 3, 2015 at 19:27

2 Answers 2

4

I would first transform the list as required and then use str.join():

>>> print (" ".join([strlist[2]] + [strlist[0]] + strlist[4:]))
c a f g h i j

Depending on your exact requirements (which are not entirely clear from your question) the transformation code might need to be different. However, the overall "transform then join" pattern still applies.

Sign up to request clarification or add additional context in comments.

1 Comment

Upvote assuming we understood this weird pattern correctly
-1

If formatting isn't an issue, then this should work:

print (" ".join(strlist)) 

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.