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]
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.
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.
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.
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 .
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 namedtuple
s ;-)
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.
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