Name format string python

format strings and named arguments in Python

It works. and it prints ’20 10′ My question is why does it work and what’s the use of named arguments in this case.

It looks like you simply renamed arg2 to arg1 and vice versa. in other words arg1 is now 20 instead of 10, which is why you see the first number in your string print 20 instead of 10. To do the test you wanted, you needed to simply move the args AND their values to the new position in the format() call and it would behave the way you expect. Nothing is out of the ordinary here.

2 Answers 2

Named replacement fields (the <. >parts in a format string) match against keyword arguments to the .format() method, and not positional arguments.

Keyword arguments are like keys in a dictionary; order doesn’t matter, as they are matched against a name.

If you wanted to match against positional arguments, use numbers:

In Python 2.7 and up, you can omit the numbers; the <> replacement fields are then auto-numbered in order of appearance in the formatting string:

The formatting string can match against both positional and keyword arguments, and can use arguments multiple times:

"    ".format(10, 20, foo='bar', ham='spam') 

The field_name itself begins with an arg_name that is either a number or a keyword. If it’s a number, it refers to a positional argument, and if it’s a keyword, it refers to a named keyword argument.

If you are creating a large formatting string, it is often much more readable and maintainable to use named replacement fields, so you don’t have to keep counting out the arguments and figure out what argument goes where into the resulting string.

You can also use the **keywords calling syntax to apply an existing dictionary to a format, making it easy to turn a CSV file into formatted output:

import csv fields = ('category', 'code', 'price', 'description', 'link', 'picture', 'plans') table_row = '''\  "> ()  ''' with open(filename, 'rb') as infile: reader = csv.DictReader(infile, fieldnames=fields, delimiter='\t') for row in reader: row['price'] = float(row['price']) # needed to make `.2f` formatting work print table_row.format(**row) 

Here, picture , link , description and price are all keys in the row dictionary, and it is much easier to see what happens when I apply the row to the formatting string.

Источник

String formatting named parameters?

So that my_url is used twice? I assume I have to «name» the %s and then use a dict in the params, but I’m not sure of the proper syntax? just FYI, I’m aware I can just use my_url twice in the params, but that’s not the point 🙂

The title of the question is a bit misleading. This has nothing to do with the print statement, just with how string interpolation works.

When you have no idea how to google it, go here to use search: python.org/doc. It’s better than Google for one important reason.

8 Answers 8

I wonder why you prefer that schmlamar? I would not have readily known what that meant, compared the the normal declaration of a dict that the OP uses.

In Python 2.6+ and Python 3, you might choose to use the newer string formatting method.

which saves you from repeating the argument, or

if you want named parameters.

which is strictly positional, and only comes with the caveat that format() arguments follow Python rules where unnamed args must come first, followed by named arguments, followed by *args (a sequence like list or tuple) and then *kwargs (a dict keyed with strings if you know what’s good for you). The interpolation points are determined first by substituting the named values at their labels, and then positional from what’s left. So, you can also do this.

print('"><>'.format(my_url, my_url, not_my_url=her_url)) 
print('"><>'.format(my_url, not_my_url=her_url, my_url)) 

The above method is not for named string formatting though, this is positional string formatting. So this does not really answer the question.

The «literal «.format(arg1=»arg!») named format works with Python 3.5, whereas the terser f»literal » is a newer innovation in Python 3.6 or newer, AFAIK.

The comment from @jaapz is no longer valid considering the changes to this answer that include the non-positional syntax print(‘»> ‘.format(url=my_url)) . This works great both with Python 2 and 3.

@uchuugaka The examples you added, even the «you can do this» one, has two placeholders but three arguments. You need to drop the second my_url . (Although it seems like it does still work — it’s just silently ignored by Python, which is a surprise to me.)

Solution in Python 3.6+

Python 3.6 introduces literal string formatting, so that you can format the named parameters without any repeating any of your named parameters outside the string:

This will evaluate my_url , so if it’s not defined you will get a NameError . In fact, instead of my_url , you can write an arbitrary Python expression, as long as it evaluates to a string (because of the :s formatting code). If you want a string representation for the result of an expression that might not be a string, replace :s by !s , just like with regular, pre-literal string formatting.

For details on literal string formatting, see PEP 498, where it was first introduced, and PEP 701, where permitted syntax was extended (starting with Python 3.12).

Источник

Читайте также:  Php current date format
Оцените статью