質問

I very like quite new Python convention to print things with .format()

Is it possible using it to print element line by line. Assuming of course number of elements is unknown.

Working example will be appreciated.

役に立ちましたか?

解決 2

You can use the string formatter on really any kind of string, including multi-line string. So of course, if you had a format string '{}\n{}\n{}' you could pass three items to it, and they would be all placed on separate lines.

So with a dynamic number of elements you want to print, all you need to do is make sure that the format string contains the same number of format items too. One way to solve this would be to construct the format string dynamically. For example this:

'\n'.join('{}' for _ in range(len(my_list))).format(*my_list)

So you essentially create a format string first, by having a generator produce one format item {} per element in my_list, and joining these using a newline character. So the resulting string looks something like this: {}\n{}\n…\n{}\n{}.

And then you use that string as the format string, and call format on it, passing the unpacked list as arguments to it. So you are correctly filling all spots of the format string.

So, you can do it. However, this is not really a practical idea. It looks rather confusing and does not convey your intention well. A better way would be to handle each item of your list separately and format it separately, and only then join them together:

'\n'.join('{}'.format(item) for item in my_list)

As for just printing elements line by line, of course, the more obvious way, that wouldn’t require you to build one long string with line breaks, would be to loop over the items and just print them one-by-one:

for item in my_list:
    print(item)

    # or use string formatting for the item here
    print('{}'.format(item))

And of course, as thefourtheye suggested, if each loop iteration is very simple, you can also pass the whole list to the print function, and set sep='\n' to print the elements on separate lines each.

他のヒント

If you are using Python 3.x and your intention is to just printing the list of elements, one in each line, then you can use print function itself, like this

my_list = [1, 2, 3, 4]
print(*my_list, sep="\n")

*my_list simply unpacks the list elements and pass each one of them as parameters to the print function (Yes, print is a function in Python 3.x).

Output

1
2
3
4

If you are using Python 2.x, then you can just import the print function from the future like this

from __future__ import print_function

Note: This import should be the first line in the file.

You mean like print('\n'.join(a_list))? String formatting could probably do something similar to '\n'.join(a_list), but it doesn't seem necessary here. (see update)

The thing is, .format doesn't print things at all. That's what print is for. format takes some data and returns a string. print is one way to output that string to the terminal/standard output, but print and .format don't really have any real relationship.

Update:

I take back what I said about string formatting being able to do this. The format pattern itself predefines the arity of the format method, so short of dynamically building the format pattern, you can't use format for this.

Keep It Simple

>>> myList = [2,3,5,6,5,4,3,2]

>>> for elem in myList:
    '{}'.format(elem)

gives

'2'
'3'
'5'
'6'
'5'
'4'
'3'
'2'

Is it what you wish obtain?

We can use join to print line by line:

>>> x = ['a','b','c']
>>> print("\n".join(x))
a
b
c

Using module pprint - Data pretty printer

>>> import pprint

>>> stuff = ['spam', 'eggs', 'lumberjack', 'knights', 'ni']

>>> stuff.insert(0, stuff[:])

>>> pp = pprint.PrettyPrinter(indent=4)

>>> pp.pprint(stuff)

[   ['spam', 'eggs', 'lumberjack', 'knights', 'ni'],
    'spam',
    'eggs',
    'lumberjack',
    'knights',
    'ni']

Another way to do it is to use string multiplication:

my_list = [1, 2, 3, 4, 5]
print(('{}\n'*len(my_list)).format(*my_list))

For plain old printing, I'd use the sep option of the print command. The format method is more useful if you are using the python logging facilities (which do not have the sep argument).

one more idea to get the string not needing to print it:

my_list = [1, 2, 3, 4]
str("{}\n"*len(my_list)).format(*my_list)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top