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?
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.
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.
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.
%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))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With