Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3 .format and List

Tags:

python-3.x

I am looking to print out results from a list built in my Python program.

I will take the results of the values in the lists and print them out separated by tabs.

I have a list called 'a' and I will just select the element to produce the final table.

But when I use the .format method, I have had to call the list four times.

a = [1,2,3,4]
print('a{[0]}\ta{[3]}\ta{[1]}\ta{[2]}'.format(a, a, a, a))

Output:

a1  a4  a2  a3

is there a better method of telling the format command to use list 'a' each time?

like image 349
zeeman Avatar asked Oct 19 '17 15:10

zeeman


People also ask

How do you format a string in a list Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

What does .format do in Python 3?

format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

How do you use two formats in Python?

Method 2: Python String format() with multiple placeholdersMultiple pairs of curly braces can be used while formatting the string in Python. Let's say another variable substitution is needed in the sentence, which can be done by adding a second pair of curly braces and passing a second value into the method.

What is %s and %D in Python?

%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))


1 Answers

You can use the *(single asterisk) to unpack the list for you. See also: Unpack a list

a = [1,2,3,4]
print('a{0}\ta{3}\ta{1}\ta{2}'.format(*a))
like image 92
Taku Avatar answered Sep 27 '22 20:09

Taku