Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting named parameters?

I know it's a really simple question, but I have no idea how to google it.

how can I do

print '<a href="%s">%s</a>' % (my_url)

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 :)

like image 406
mpen Avatar asked Mar 16 '10 02:03

mpen


People also ask

What is string formatting in Python?

String formatting is the process of infusing things in the string dynamically and presenting the string. There are four different ways to perform string formatting:- Formatting with % Operator. Formatting with format() string method. Formatting with string literals, called f-strings.

What is string format () in Java?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.


8 Answers

print '<a href="%(url)s">%(url)s</a>' % {'url': my_url}
like image 181
Ignacio Vazquez-Abrams Avatar answered Oct 13 '22 01:10

Ignacio Vazquez-Abrams


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

print('<a href="{0}">{0}</a>'.format(my_url))

which saves you from repeating the argument, or

print('<a href="{url}">{url}</a>'.format(url=my_url))

if you want named parameters.

print('<a href="{}">{}</a>'.format(my_url, my_url))

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('<a href="{not_my_url}">{}</a>'.format(my_url, my_url, not_my_url=her_url))

But not this...

print('<a href="{not_my_url}">{}</a>'.format(my_url, not_my_url=her_url, my_url))
like image 24
Greg Ball Avatar answered Oct 12 '22 23:10

Greg Ball


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:

print(f'<a href="{my_url:s}">{my_url:s}</a>')

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.

like image 26
gerrit Avatar answered Oct 12 '22 23:10

gerrit


You will be addicted to syntax.

Also C# 6.0, EcmaScript developers has also familier this syntax.

In [1]: print '{firstname} {lastname}'.format(firstname='Mehmet', lastname='Ağa')
Mehmet Ağa

In [2]: print '{firstname} {lastname}'.format(**dict(firstname='Mehmet', lastname='Ağa'))
Mehmet Ağa
like image 34
guneysus Avatar answered Oct 13 '22 00:10

guneysus


For building HTML pages, you want to use a templating engine, not simple string interpolation.

like image 40
Mike Graham Avatar answered Oct 12 '22 23:10

Mike Graham


Another option is to use format_map:

print('<a href="{s}">{s}</a>'.format_map({'s': 'my_url'}))
like image 31
Danny Varod Avatar answered Oct 13 '22 00:10

Danny Varod


As well as the dictionary way, it may be useful to know the following format:

print '<a href="%s">%s</a>' % (my_url, my_url)

Here it's a tad redundant, and the dictionary way is certainly less error prone when modifying the code, but it's still possible to use tuples for multiple insertions. The first %s is substituted for the first element in the tuple, the second %s is substituted for the second element in the tuple, and so on for each element in the tuple.

like image 44
Ponkadoodle Avatar answered Oct 12 '22 23:10

Ponkadoodle


I recommend this syntax

dictionary_of_string_values = {
                               "my_text" : "go to w3schools",
                               "my_url" : "https://www.w3schools.com",
                               }

print ('<a href="{my_url}">{my_text}</a>'.format(**dictionary_of_string_values))

It is very useful when you have to format a string with lots of placeholders.

You can also make it shorter like this:

print ('<a href="{my_url}">{my_text}</a>'.format(
                             **{
                               "my_text" : "go to w3schools",
                               "my_url" : "https://www.w3schools.com",
                               }
                            )
                        )
like image 21
Tms91 Avatar answered Oct 12 '22 23:10

Tms91