Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a list not allowed with format strings?

Why is a tuple (or dict) mandatory for use with a format string:

"%s %d" % ("text", 42)

What would be the disadvantage of the following?

"%s %d" % ["text", 42]
like image 395
steffen Avatar asked Jun 01 '15 18:06

steffen


People also ask

Can a list have strings?

To create a list of strings, first use square brackets [ and ] to create a list. Then place the list items inside the brackets separated by commas. Remember that strings must be surrounded by quotes. Also remember to use = to store the list in a variable.

How do I format a list to a string in 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.

Is a list considered a string?

Answer. Strings and lists share many similarities as we have seen throughout this lesson. However, strings are not interchangeable with lists because of some important differences. Strings can only consist of characters, while lists can contain any data type.

Why do we use format string?

Format provides give you great flexibility over the output of the string in a way that is easier to read, write and maintain than just using plain old concatenation. Additionally, it's easier to get culture concerns right with String. Format .


1 Answers

I'm guessing, but I expect it's because GvR wanted to minimise the number of different types T for which 'my object is: %s' % T(...) fails. It's bad enough that it fails for namedtuples ;-)

That is to say, allowing '%s %s' % [1,2] creates an extra trap for the unwary, because it prevents you formatting [1,2] itself with the %s format.

like image 106
2 revs Avatar answered Oct 02 '22 16:10

2 revs